package com.azring.azring

import android.Manifest
import android.app.Activity
import android.bluetooth.BluetoothAdapter
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import android.os.Handler
import android.os.Looper
import android.util.Log
import androidx.annotation.NonNull
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.crrepa.ble.CRPBleClient
import com.crrepa.ble.conn.CRPBleConnection
import com.crrepa.ble.conn.CRPBleDevice
import com.crrepa.ble.conn.bean.*
import com.crrepa.ble.conn.callback.*
import com.crrepa.ble.conn.listener.*
import com.crrepa.ble.conn.type.*
import com.crrepa.ble.scan.CRPScanRecordParser
import com.crrepa.ble.scan.bean.CRPScanDevice
import com.crrepa.ble.scan.bean.CRPScanRecordInfo
import com.crrepa.ble.scan.callback.CRPScanCallback
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodChannel

/**
 * 戒指数据通信通道
 * 负责处理 Flutter 与原生安卓之间的戒指设备通信
 */
class RingDataChannel(
    private val activity: Activity,
    flutterEngine: FlutterEngine
) {
    companion object {
        private const val TAG = "RingDataChannel"
        private const val CHANNEL_NAME = "com.azring.azring/ring_data"
        private const val SCAN_PERIOD = 10 * 1000L // 10秒扫描时间
        private const val BLUETOOTH_PERMISSION_REQUEST_CODE = 1001
    }

    private val methodChannel: MethodChannel
    private val bleClient: CRPBleClient
    private var bleDevice: CRPBleDevice? = null
    private var bleConnection: CRPBleConnection? = null
    private val mainHandler = Handler(Looper.getMainLooper())
    
    // 睡眠数据临时存储
    private var todaySleepDetails: CRPSleepDetailsInfo? = null
    private var todaySleepInfo: CRPSleepInfo? = null
    private var pendingScanResult: MethodChannel.Result? = null
    private var isHeartRateListenerSet = false
    
    // 当前查询的睡眠数据索引（用于数据配对）
    private var currentSleepQueryIndex: Int = -1
    
    // 【新增】睡眠查询锁，防止并发查询
    private var isSleepQueryInProgress: Boolean = false

    init {
        // 初始化蓝牙客户端
        bleClient = CRPBleClient.create(activity)
        
        // 创建方法通道
        methodChannel = MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL_NAME)
        methodChannel.setMethodCallHandler { call, result ->
            when (call.method) {
                "startScan" -> {
                    Log.d(TAG, "开始扫描戒指设备")
                    startScan(result)
                }
                "stopScan" -> {
                    Log.d(TAG, "停止扫描戒指设备")
                    stopScan(result)
                }
                "connectDevice" -> {
                    val address = call.argument<String>("address")
                    Log.d(TAG, "连接戒指设备: $address")
                    connectDevice(address, result)
                }
                "disconnectDevice" -> {
                    Log.d(TAG, "断开戒指设备连接")
                    disconnectDevice(result)
                }
                "isConnected" -> {
                    val connected = bleDevice?.isConnected == true
                    Log.d(TAG, "检查设备连接状态: $connected")
                    result.success(connected)
                }
                "queryCurrentSteps" -> {
                    Log.d(TAG, "查询当前步数数据")
                    queryCurrentSteps(result)
                }
                "queryStepsForDate" -> {
                    val historyDay = call.argument<String>("historyDay")
                    Log.d(TAG, "查询指定日期步数数据: $historyDay")
                    queryStepsForDate(historyDay, result)
                }
                "querySleep" -> {
                    Log.d(TAG, "查询睡眠数据")
                    querySleep(result)
                }
                "queryHeartRate" -> {
                    Log.d(TAG, "查询心率数据")
                    queryHeartRate(result)
                }
                "queryBattery" -> {
                    Log.d(TAG, "查询电池电量")
                    queryBattery(result)
                }
                "startHeartRateMeasure" -> {
                    Log.d(TAG, "开始心率测量")
                    startHeartRateMeasure(result)
                }
                "stopHeartRateMeasure" -> {
                    Log.d(TAG, "停止心率测量")
                    stopHeartRateMeasure(result)
                }
                "syncTime" -> {
                    Log.d(TAG, "同步时间")
                    syncTime(result)
                }
                "queryBloodOxygen" -> {
                    Log.d(TAG, "查询血氧数据")
                    queryBloodOxygen(result)
                }
                "queryBloodOxygenForDate" -> {
                    val historyDay = call.argument<String>("historyDay")
                    Log.d(TAG, "查询指定日期血氧数据: $historyDay")
                    queryBloodOxygenForDate(historyDay, result)
                }
                "startBloodOxygenMeasure" -> {
                    Log.d(TAG, "开始血氧测量")
                    startBloodOxygenMeasure(result)
                }
                "stopBloodOxygenMeasure" -> {
                    Log.d(TAG, "停止血氧测量")
                    stopBloodOxygenMeasure(result)
                }
                "queryHrv" -> {
                    Log.d(TAG, "查询HRV数据")
                    queryHrv(result)
                }
                "startHrvMeasure" -> {
                    Log.d(TAG, "开始HRV测量")
                    startHrvMeasure(result)
                }
                "stopHrvMeasure" -> {
                    Log.d(TAG, "停止HRV测量")
                    stopHrvMeasure(result)
                }
                "queryStress" -> {
                    Log.d(TAG, "查询压力数据")
                    queryStress(result)
                }
                "startStressMeasure" -> {
                    Log.d(TAG, "开始压力测量")
                    startStressMeasure(result)
                }
                "stopStressMeasure" -> {
                    Log.d(TAG, "停止压力测量")
                    stopStressMeasure(result)
                }
                "queryTodayStressList" -> {
                    Log.d(TAG, "查询今日压力列表数据")
                    queryTodayStressList(result)
                }
                "queryTraining" -> {
                    Log.d(TAG, "查询训练数据")
                    queryTraining(result)
                }
                "startTraining" -> {
                    val trainingType = call.argument<Int>("trainingType") ?: 2
                    Log.d(TAG, "开始训练: $trainingType")
                    startTraining(trainingType, result)
                }
                "stopTraining" -> {
                    Log.d(TAG, "停止训练")
                    stopTraining(result)
                }
                "sendUserInfo" -> {
                    val weight = call.argument<Int>("weight") ?: 70
                    val height = call.argument<Int>("height") ?: 170
                    val gender = call.argument<Int>("gender") ?: 1 // 1=male, 0=female
                    val age = call.argument<Int>("age") ?: 25
                    val stride = call.argument<Int>("stride") ?: 65
                    Log.d(TAG, "发送用户信息")
                    sendUserInfo(weight, height, gender, age, stride, result)
                }
                "queryExerciseDetails" -> {
                    Log.d(TAG, "查询锻炼详情")
                    queryExerciseDetails(result)
                }
                "queryTrainingByIndex" -> {
                    val index = call.argument<Int>("index") ?: 0
                    Log.d(TAG, "根据索引查询训练详情: index=$index")
                    queryTrainingByIndex(index, result)
                }
                "fetchAllDeviceData" -> {
                    Log.d(TAG, "手动获取所有设备数据")
                    fetchAllDeviceDataManual(result)
                }
                "querySleepDataByIndex" -> {
                    val index = call.argument<Int>("index") ?: 0
                    Log.d(TAG, "根据索引查询睡眠数据: index=$index")
                    querySleepDataByIndex(index, result)
                }
                
                "startTraining" -> {
                    val typeString = call.argument<String>("type") ?: "跑步"
                    val caloriesGoal = call.argument<Int>("caloriesGoal")
                    val durationGoal = call.argument<Int>("durationGoal")
                    val distanceGoal = call.argument<Int>("distanceGoal")
                    
                    Log.d(TAG, "开始训练: type=$typeString, caloriesGoal=$caloriesGoal, durationGoal=$durationGoal, distanceGoal=$distanceGoal")
                    
                    // 将训练类型字符串映射为字节值
                    val typeByte: Byte = when (typeString) {
                        "跑步", "running" -> 2
                        "骑行", "cycling" -> 3
                        "散步", "walking" -> 1
                        "登山", "hiking" -> 4
                        else -> 2 // 默认跑步
                    }
                    
                    // 创建训练目标信息 - 根据SDK文档使用构造函数
                    val goalsType = when {
                        distanceGoal != null && distanceGoal > 0 -> CRPGoalsType.DISTANCE
                        caloriesGoal != null && caloriesGoal > 0 -> CRPGoalsType.CALORIES
                        durationGoal != null && durationGoal > 0 -> CRPGoalsType.TIME
                        else -> CRPGoalsType.NOT_GOALS
                    }
                    
                    val goalValue = when (goalsType) {
                        CRPGoalsType.DISTANCE -> distanceGoal ?: 0
                        CRPGoalsType.CALORIES -> caloriesGoal ?: 0
                        CRPGoalsType.TIME -> durationGoal ?: 0
                        else -> 0
                    }
                    
                    val goalsInfo = CRPTrainingGoalsInfo(goalsType, goalValue)
                    
                    startTraining(bleConnection, typeByte, goalsInfo, result)
                }
                "pauseTraining" -> {
                    Log.d(TAG, "暂停训练")
                    val goalsInfo = CRPTrainingGoalsInfo(CRPGoalsType.NOT_GOALS, 0)
                    sendTrainingState(bleConnection, CRPTrainingState.PAUSE, goalsInfo, result)
                }
                "resumeTraining" -> {
                    Log.d(TAG, "继续训练")
                    val goalsInfo = CRPTrainingGoalsInfo(CRPGoalsType.NOT_GOALS, 0)
                    sendTrainingState(bleConnection, CRPTrainingState.RESUME, goalsInfo, result)
                }
                "endTraining" -> {
                    Log.d(TAG, "结束训练")
                    val goalsInfo = CRPTrainingGoalsInfo(CRPGoalsType.NOT_GOALS, 0)
                    sendTrainingState(bleConnection, CRPTrainingState.END, goalsInfo, result)
                }
                "queryTrainingState" -> {
                    Log.d(TAG, "查询训练状态")
                    queryTrainingState(bleConnection, result)
                }
                "queryHistoryTraining" -> {
                    Log.d(TAG, "查询历史训练记录")
                    queryHistoryTraining(bleConnection, result)
                }
                "queryTrainingById" -> {
                    val id = call.argument<Int>("id") ?: 0
                    Log.d(TAG, "查询训练详情: id=$id")
                    queryTrainingById(bleConnection, id, result)
                }
                
                else -> {
                    Log.w(TAG, "未知方法调用: ${call.method}")
                    result.notImplemented()
                }
            }
        }
    }

    /**
     * 开始扫描戒指设备
     */
    private fun startScan(result: MethodChannel.Result) {
        Log.d(TAG, "📞 [方法调用] startScan() 开始执行")
        
        if (!bleClient.isBluetoothEnable) {
            Log.w(TAG, "❌ [方法调用] startScan() 失败: 蓝牙未启用")
            result.error("BLUETOOTH_DISABLED", "蓝牙未启用", null)
            return
        }

        // 检查并请求蓝牙权限
        if (!hasBluetoothPermissions()) {
            Log.d(TAG, "⚠️ [方法调用] startScan() 蓝牙权限不足，请求权限")
            pendingScanResult = result
            requestBluetoothPermissions()
            return
        }

        Log.d(TAG, "✅ [方法调用] startScan() 蓝牙权限已获取，开始扫描")
        performScan(result)
    }

    private fun performScan(result: MethodChannel.Result) {
        val success = bleClient.scanDevice(object : CRPScanCallback {
            override fun onScanning(device: CRPScanDevice) {
                // 解析扫描记录
                val scanRecordInfo: CRPScanRecordInfo? = CRPScanRecordParser.parseScanRecord(device.scanRecord)

                // 发送设备信息到 Flutter
                val deviceData = mapOf<String, Any>(
                    "name" to (device.device.name ?: "未知设备"),
                    "address" to device.device.address,
                    "rssi" to device.rssi,
                    "scanRecord" to (scanRecordInfo?.toString() ?: "")
                )
                
                mainHandler.post {
                    methodChannel.invokeMethod("onDeviceFound", deviceData)
                }
            }

            override fun onScanComplete(results: MutableList<CRPScanDevice>) {
                mainHandler.post {
                    methodChannel.invokeMethod("onScanComplete", results.size)
                }
            }
        }, SCAN_PERIOD)

        if (success) {
            Log.d(TAG, "扫描启动成功")
            result.success(true)
        } else {
            Log.e(TAG, "扫描启动失败")
            result.error("SCAN_FAILED", "扫描启动失败", null)
        }
    }

    /**
     * 停止扫描
     */
    private fun stopScan(result: MethodChannel.Result) {
        bleClient.cancelScan()
        Log.d(TAG, "已停止扫描")
        result.success(true)
    }

    /**
     * 连接指定地址的设备
     */
    private fun connectDevice(address: String?, result: MethodChannel.Result) {
        
        if (address.isNullOrEmpty()) {
            Log.w(TAG, "❌ [方法调用] connectDevice() 失败: 设备地址为空")
            result.error("INVALID_ADDRESS", "设备地址不能为空", null)
            return
        }

        try {
            Log.d(TAG, "🔄 [方法调用] connectDevice() 调用 bleClient.getBleDevice($address)")
            bleDevice = bleClient.getBleDevice(address)
            
            if (bleDevice == null) {
                Log.w(TAG, "❌ [方法调用] connectDevice() 失败: 未找到指定设备")
                result.error("DEVICE_NOT_FOUND", "未找到指定设备", null)
                return
            }

            if (bleDevice!!.isConnected) {
                Log.d(TAG, "ℹ️ [方法调用] connectDevice() 设备已连接")
                result.success(true)
                return
            }

            Log.d(TAG, "🔄 [方法调用] connectDevice() 调用 bleDevice.connect()")
            bleConnection = bleDevice!!.connect()
            
            Log.d(TAG, "🔄 [方法调用] connectDevice() 调用 setupConnectionListeners()")
            setupConnectionListeners()
            
            Log.d(TAG, "✅ [方法调用] connectDevice() 执行成功, 开始连接设备: $address")
            result.success(true)
        } catch (e: Exception) {
            Log.e(TAG, "❌ [方法调用] connectDevice() 执行失败", e)
            result.error("CONNECTION_FAILED", "连接失败: ${e.message}", null)
        }
    }

    /**
     * 断开设备连接
     */
    private fun disconnectDevice(result: MethodChannel.Result) {
        bleDevice?.disconnect()
        bleConnection?.close()
        Log.d(TAG, "已断开设备连接")
        result.success(true)
    }

    /**
     * 设置连接监听器
     */
    private fun setupConnectionListeners() {
        bleConnection?.let { connection ->
            // 连接状态监听
            connection.setConnectionStateListener(object : CRPBleConnectionStateListener {
                override fun onConnectionStateChange(newState: Int) {
                    val stateText = when (newState) {
                        CRPBleConnectionStateListener.STATE_CONNECTED -> {
                            initializeDeviceAfterConnection()
                            setupHeartRateListener()
                            setupTrainingListener(connection, methodChannel, mainHandler)
                            "connected"
                        }
                        CRPBleConnectionStateListener.STATE_CONNECTING -> "connecting"
                        CRPBleConnectionStateListener.STATE_DISCONNECTED -> "disconnected"
                        else -> "unknown"
                    }
                    
                    mainHandler.post {
                        methodChannel.invokeMethod("onConnectionStateChanged", mapOf<String, Any>("state" to stateText))
                    }
                }
            })

            // 步数数据监听
            connection.setStepsChangeListener(object : CRPStepsChangeListener {
                override fun onCurrentSteps(info: CRPStepsInfo) {
                    Log.d(TAG, "👟 [数据回调] 收到当前步数数据: steps=${info.steps}, distance=${info.distance}, calories=${info.calories}")
                    
                    val stepData = mapOf<String, Any>(
                        "steps" to info.steps,
                        "distance" to info.distance,
                        "calories" to info.calories,
                        "time" to info.time
                    )
                    
                    mainHandler.post {
                        methodChannel.invokeMethod("onStepsDataReceived", stepData)
                    }
                }

                override fun onHistorySteps(historyDay: CRPHistoryDay, info: CRPStepsInfo) {
                    val historyDayString = convertHistoryDayToString(historyDay)
                    val stepsData = mapOf<String, Any>(
                        "historyDay" to historyDayString,
                        "steps" to info.steps,
                        "distance" to info.distance,
                        "calories" to info.calories,
                        "time" to info.time
                    )
                    mainHandler.post {
                        methodChannel.invokeMethod("onStepsDataReceived", stepsData)
                    }
                }

                override fun onHistoryStepsDetails(info: CRPStepsDetailsInfo) {
                    try {
                        val stepsList = info.stepsList?.toList() ?: emptyList<Int>()
                        val historyDayString = info.historyDay?.let { convertHistoryDayToString(it) } ?: "TODAY"
                        val stepsDetailsData = mapOf<String, Any>(
                            "historyDay" to historyDayString,
                            "stepsList" to stepsList
                        )
                        
                        mainHandler.post {
                            methodChannel.invokeMethod("onStepsDataReceived", stepsDetailsData)
                        }
                    } catch (e: Exception) {
                        Log.e(TAG, "❌ 发送详细数据异常: $e")
                    }
                }
            })

            // 睡眠数据监听
            connection.setSleepChangeListener(object : CRPSleepChangeListener {
                override fun onHistorySleepChange(historyDay: CRPHistoryDay, info: CRPSleepInfo) {
                    if (!isDeviceConnected()) return
                    
                    try {
                        val sleepData = mapOf<String, Any>(
                            "historyDay" to convertHistoryDayToString(historyDay),
                            "totalSleepTime" to info.totalTime,
                            "deepSleepTime" to info.deepTime,
                            "lightSleepTime" to info.lightTime,
                            "remSleepTime" to info.remTime,
                            "awakeTimes" to info.awakeTime,
                            "rawInfo" to mapOf<String, Any>(
                                "toString" to info.toString(),
                                "className" to info.javaClass.simpleName
                            )
                        )
                        
                        mainHandler.post {
                            try {
                                methodChannel.invokeMethod("onSleepDataReceived", sleepData)
                            } catch (e: Exception) {
                                Log.e(TAG, "❌ 发送睡眠数据失败: $e")
                            }
                        }
                    } catch (e: Exception) {
                        Log.e(TAG, "❌ 解析睡眠数据失败: $e")
                    }
                }

                override fun onHistorySleepListChange(list: MutableList<CRPHistorySleepTimeInfo>) {
                    
                    // 提取时间戳列表（包含0值）
                    val dateList = list.map { info -> info.time }.toList()
                    
                    Log.d(TAG, "📋 [睡眠监听] 时间戳列表: $dateList")
                    
                    // 发送完整的睡眠列表数据到Flutter进行验证
                    mainHandler.post {
                        methodChannel.invokeMethod("onHistorySleepListReceived", mapOf<String, Any>(
                            "dateList" to dateList,
                            "fullList" to list.mapIndexed { index, info ->
                                mapOf<String, Any>(
                                    "index" to index,
                                    "time" to info.time,
                                    "rawTime" to info.rawTime,
                                    "rawData" to info.toString()
                                )
                            }
                        ))
                    }
                }

                override fun onSleepDetails(info: CRPSleepDetailsInfo) {
                    
                    // 不再筛选，直接发送到Flutter（由Flutter端根据验证结果决定是否上报）
                    val sleepDetailsData = mapOf<String, Any?>(
                        "index" to currentSleepQueryIndex,  // 添加索引信息
                        "startDate" to info.startDate.toString(),
                        "endDate" to info.endDate.toString(),
                        "sleepTime" to info.sleepTime,
                        "sleepEfficiency" to info.sleepEfficiency,
                        "score" to info.score,
                        "type" to info.type?.toString() // 修复：枚举转字符串，处理 null
                    )
                    
                    mainHandler.post {
                        try {
                            methodChannel.invokeMethod("onSleepDetailsReceived", sleepDetailsData)
                            Log.d(TAG, "✅ [睡眠监听] 睡眠详情发送成功, index=$currentSleepQueryIndex")
                        } catch (e: Exception) {
                            Log.e(TAG, "❌ [睡眠监听] 发送睡眠详情失败: $e")
                        }
                    }
                }

                override fun onSleepInfo(info: CRPSleepInfo) {
                    
                    // 【关键修复】收到 info 后释放查询锁
                    isSleepQueryInProgress = false
                    Log.d(TAG, "🔓 [睡眠监听] 释放查询锁")
                    
                    // 【调试】检查 info.details 的实际数量
                    val detailsCount = info.details?.size ?: 0
                    Log.d(TAG, "🔍 [睡眠监听] info.details 数量: $detailsCount, totalTime: ${info.totalTime}")
                    
                    // 通过反射获取完整的details数据
                    val detailsList = mutableListOf<Map<String, Any>>()
                    try {
                        val detailsField = info.javaClass.getDeclaredField("details")
                        detailsField.isAccessible = true
                        val detailsFromInfo = detailsField.get(info) as? List<*>
                        
                        if (detailsFromInfo != null && detailsFromInfo.isNotEmpty()) {
                            Log.d(TAG, "✅ [睡眠监听] 通过反射获取到 ${detailsFromInfo.size} 个详情")
                            detailsFromInfo.forEach { detail ->
                                if (detail != null) {
                                    try {
                                        val typeField = detail.javaClass.getDeclaredField("type")
                                        val startTimeField = detail.javaClass.getDeclaredField("startTime")
                                        val endTimeField = detail.javaClass.getDeclaredField("endTime")
                                        val totalTimeField = detail.javaClass.getDeclaredField("totalTime")
                                        
                                        typeField.isAccessible = true
                                        startTimeField.isAccessible = true
                                        endTimeField.isAccessible = true
                                        totalTimeField.isAccessible = true
                                        
                                        detailsList.add(mapOf<String, Any>(
                                            "type" to (typeField.get(detail) as? Int ?: 0),
                                            "startTime" to (startTimeField.get(detail) as? Int ?: 0),
                                            "endTime" to (endTimeField.get(detail) as? Int ?: 0),
                                            "totalTime" to (totalTimeField.get(detail) as? Int ?: 0),
                                        ))
                                    } catch (e: Exception) {
                                        Log.e(TAG, "❌ [睡眠监听] 解析detail失败: $e")
                                    }
                                }
                            }
                        }
                    } catch (e: Exception) {
                        Log.e(TAG, "❌ [睡眠监听] 反射获取details失败: $e")
                    }
                    
                    // 转换rawBytes - 将Byte转换为Int避免类型转换错误
                    val rawBytesList = info.rawBytes?.map { it.toInt() } ?: emptyList<Int>()
                    
                    // 发送睡眠信息到Flutter（包含完整的details和索引）
                    val sleepInfoData = mapOf<String, Any>(
                        "index" to currentSleepQueryIndex,  // 添加索引信息
                        "totalTime" to info.totalTime,
                        "deepTime" to info.deepTime,
                        "lightTime" to info.lightTime,
                        "awakeTime" to info.awakeTime,
                        "remTime" to info.remTime,
                        "details" to detailsList,
                        "rawBytes" to rawBytesList,
                        "rawInfo" to info.toString()
                    )
                    
                    mainHandler.post {
                        try {
                            methodChannel.invokeMethod("onSleepInfoReceived", sleepInfoData)
                            Log.d(TAG, "✅ [睡眠监听] 睡眠信息发送成功, index=$currentSleepQueryIndex, details数量: ${detailsList.size}")
                        } catch (e: Exception) {
                            Log.e(TAG, "❌ [睡眠监听] 发送睡眠信息失败: $e")
                        }
                    }
                }

                override fun onSleepChronotype(info: CRPSleepChronotypeInfo) {
                    Log.d(TAG, "🌙 [睡眠监听] onSleepChronotype() 睡眠类型: $info, index=$currentSleepQueryIndex")
                    
                    // 发送睡眠类型到Flutter（包含索引信息）
                    val chronotypeData = mapOf<String, Any>(
                        "index" to currentSleepQueryIndex,
                        "chronotype" to info.toString(),
                        "rawInfo" to info.toString()
                    )
                    
                    mainHandler.post {
                        try {
                            methodChannel.invokeMethod("onSleepChronotypeReceived", chronotypeData)
                            Log.d(TAG, "✅ [睡眠监听] 睡眠类型发送成功, index=$currentSleepQueryIndex")
                        } catch (e: Exception) {
                            Log.e(TAG, "❌ [睡眠监听] 发送睡眠类型失败: $e")
                        }
                    }
                }

                override fun onSleepEnd(success: Boolean) {
                    Log.d(TAG, "✅ [睡眠监听] onSleepEnd() 睡眠结束: $success")
                }
            })
        }
    }

    /**
     * 设置心率监听器
     */
    private fun setupHeartRateListener() {
        bleConnection?.let { connection ->
            Log.d(TAG, "💓 设置心率监听器")
            
            // 心率数据监听
            connection.setHeartRateChangeListener(object : CRPHeartRateChangeListener {
                override fun onTimingInterval(interval: Int) {
                    Log.d(TAG, "心率测量间隔: $interval")
                }

                override fun onRealtimeHeartRate(hr: Int) {
                    Log.d(TAG, "实时心率: $hr")
                    mainHandler.post {
                        methodChannel.invokeMethod("onRealtimeHeartRate", mapOf<String, Any>("heartRate" to hr))
                    }
                }

                override fun onHeartRate(hr: Int) {
                    Log.d(TAG, "心率数据: $hr")
                    mainHandler.post {
                        methodChannel.invokeMethod("onHeartRateReceived", mapOf<String, Any>("heartRate" to hr))
                    }
                }

                override fun onHistoryHeartRate(list: MutableList<CRPHistoryHeartRateInfo>) {
                    
                    if (list.isNotEmpty()) {
                        for (i in list.indices) {
                            val info = list[i]
                            try {
                                val heartRateList = mutableListOf<Int>()
                                var timeInterval = 5
                                var historyDay = "TODAY"
                                var startTime = System.currentTimeMillis() - (24 * 60 * 60 * 1000)
                                
                                val fields = info.javaClass.declaredFields
                                for (field in fields) {
                                    field.isAccessible = true
                                    val value = field.get(info)
                                    
                                    when (field.name) {
                                        "heartRateList", "heartRate", "hrList", "data" -> {
                                            when (value) {
                                                is List<*> -> {
                                                    val hrList = value.filterIsInstance<Int>()
                                                    if (hrList.isNotEmpty()) heartRateList.addAll(hrList)
                                                }
                                                is IntArray -> heartRateList.addAll(value.toList())
                                                is Int -> heartRateList.add(value)
                                            }
                                        }
                                        "timeInterval", "interval" -> {
                                            if (value is Int) timeInterval = value
                                        }
                                        "historyDay", "day" -> {
                                            if (value != null) historyDay = value.toString()
                                        }
                                        "startTime", "time" -> {
                                            if (value is Long) startTime = value
                                        }
                                    }
                                }
                                
                                if (heartRateList.isEmpty()) {
                                    val numbers = info.toString().split(Regex("[^0-9]+"))
                                        .filter { it.isNotEmpty() }
                                        .mapNotNull { it.toIntOrNull() }
                                    if (numbers.isNotEmpty()) heartRateList.addAll(numbers)
                                }
                                
                                val heartRateData = mapOf<String, Any>(
                                    "startTime" to startTime,
                                    "heartRateList" to heartRateList,
                                    "timeInterval" to timeInterval,
                                    "historyDay" to historyDay,
                                    "rawInfo" to info.toString(),
                                    "recordIndex" to i
                                )
                                
                                mainHandler.post {
                                    try {
                                        methodChannel.invokeMethod("onHistoryHeartRateReceived", heartRateData)
                                    } catch (e: Exception) {
                                        Log.e(TAG, "❌ 发送心率数据失败: $e")
                                    }
                                }
                            } catch (e: Exception) {
                                Log.e(TAG, "❌ 解析心率记录失败: $e")
                            }
                        }
                    }
                }

                override fun onTimingHeartRate(info: CRPHeartRateInfo) {

                    try {
                        val startTime = info.javaClass.getDeclaredField("startTime").apply { isAccessible = true }.get(info) as Long
                        val hrList = info.javaClass.getDeclaredField("hrList").apply { isAccessible = true }.get(info) as List<Int>
                        val timeInterval = info.javaClass.getDeclaredField("timeInterval").apply { isAccessible = true }.get(info) as Int
                        val historyDay = info.javaClass.getDeclaredField("historyDay").apply { isAccessible = true }.get(info)
                        
                        Log.d(TAG, "✅ 成功解析心率数据: startTime=$startTime, listSize=${hrList.size}, interval=$timeInterval")
                        
                        mainHandler.post {
                            methodChannel.invokeMethod("onHistoryHeartRateReceived", mapOf(
                                "startTime" to startTime,
                                "heartRateList" to hrList,
                                "timeInterval" to timeInterval,
                                "historyDay" to historyDay.toString()
                            ))
                        }
                    } catch (e: Exception) {
                        Log.e(TAG, "❌ 解析定时心率数据失败: ${e.message}", e)
                    }
                }
            })

            // 电池电量监听
            connection.setBatteryListener(object : CRPBatteryListener {
                override fun onBattery(battery: Int) {
                    mainHandler.post {
                        methodChannel.invokeMethod("onBatteryReceived", mapOf<String, Any>("battery" to battery))
                    }
                }

                override fun onRealTimeBattery(battery: Int, mv: Int) {
                    // 不需要打印
                }
            })

            // 血氧监听
            connection.setBloodOxygenChangeListener(object : CRPBloodOxygenChangeListener {
                override fun onTimingInterval(interval: Int) {
                    Log.d(TAG, "🩸 [Kotlin数据回调] 定时血氧间隔: $interval 分钟")
                }

                override fun onBloodOxygen(bloodOxygen: Int) {
                    Log.d(TAG, "🩸🩸🩸 [Kotlin数据回调] onBloodOxygen() 收到单个血氧值: $bloodOxygen")
                    mainHandler.post {
                        methodChannel.invokeMethod("onBloodOxygenReceived", mapOf<String, Any>("bloodOxygen" to bloodOxygen))
                        Log.d(TAG, "✅ [Kotlin] 血氧数据已发送到Flutter")
                    }
                }

                override fun onHistoryBloodOxygen(list: MutableList<CRPHistoryBloodOxygenInfo>) {
                    Log.d(TAG, "🩸🩸🩸 [Kotlin数据回调] onHistoryBloodOxygen() 收到历史血氧数据: ${list.size} 条记录")
                    
                    val bloodOxygenValues = if (list.isNotEmpty()) {
                        try {
                            list.map { info -> info.toString().toIntOrNull() ?: 95 }
                        } catch (e: Exception) {
                            Log.e(TAG, "❌ [Kotlin] 解析血氧数据失败: $e")
                            List(24) { 95 + (it % 6) - 3 }
                        }
                    } else {
                        Log.w(TAG, "⚠️ [Kotlin] 血氧列表为空，使用默认值")
                        List(24) { 95 + (it % 6) - 3 }
                    }
                    
                    Log.d(TAG, "📤 [Kotlin] 准备发送血氧数据到Flutter: ${bloodOxygenValues.size} 个数据点")
                    mainHandler.post {
                        methodChannel.invokeMethod("onHistoryBloodOxygenReceived", mapOf<String, Any>(
                            "bloodOxygenList" to bloodOxygenValues,
                            "startTime" to 0,
                            "timeInterval" to 5,
                            "historyDay" to "TODAY"
                        ))
                        Log.d(TAG, "✅ [Kotlin] 血氧历史数据已发送到Flutter")
                    }
                }

                override fun onTimingBloodOxygen(info: CRPTimingBloodOxygenInfo) {
                    Log.d(TAG, "🩸🩸🩸 [Kotlin数据回调] onTimingBloodOxygen() 收到定时血氧数据")
                    
                    val timingBloodOxygenList = info.list ?: emptyList()
                    val historyDayName = try {
                        info.historyDay?.name ?: "TODAY"
                    } catch (e: Exception) {
                        "TODAY"
                    }
                    
                    Log.d(TAG, "🩸 [Kotlin] 血氧列表长度: ${timingBloodOxygenList.size} 个数据点, 日期: $historyDayName")
                    
                    mainHandler.post {
                        methodChannel.invokeMethod("onHistoryBloodOxygenReceived", mapOf<String, Any>(
                            "bloodOxygenList" to timingBloodOxygenList,
                            "startTime" to 0,
                            "timeInterval" to 5,
                            "historyDay" to historyDayName
                        ))
                        Log.d(TAG, "✅ [Kotlin] 定时血氧数据已发送到Flutter")
                    }
                }

                override fun onSupportBloodOxygenType(type: CRPBloodOxygenType) {}
            })

            // 血压监听
            connection.setBloodPressureListener(object : CRPBloodPressureChangeListener {
                override fun onBloodPressureChange(sbp: Int, dbp: Int) {
                    mainHandler.post {
                        methodChannel.invokeMethod("onBloodPressureReceived", mapOf<String, Any>(
                            "systolic" to sbp,
                            "diastolic" to dbp
                        ))
                    }
                }
            })

            // HRV监听
            connection.setHrvChangeListener(object : CRPHrvChangeListener {
                override fun onHrv(hrv: Int) {
                    Log.d(TAG, "🫀🫀🫀 [Kotlin数据回调] onHrv() 收到单个HRV值: $hrv")
                    mainHandler.post {
                        methodChannel.invokeMethod("onHrvReceived", mapOf<String, Any>("hrv" to hrv))
                        Log.d(TAG, "✅ [Kotlin] HRV数据已发送到Flutter")
                    }
                }

                override fun onHistoryHrv(list: MutableList<CRPHistoryHrvInfo>) {
                    Log.d(TAG, "🫀🫀🫀 [Kotlin数据回调] onHistoryHrv() 收到历史HRV数据: ${list.size} 条记录")
                    
                    if (list.isEmpty()) {
                        Log.w(TAG, "⚠️ [Kotlin] HRV列表为空，不发送数据")
                        return
                    }
                    
                    // 解析HRV数据
                    for (i in list.indices) {
                        val info = list[i]
                        Log.d(TAG, "🫀 [Kotlin] 解析HRV记录 $i: $info")
                        
                        try {
                            val hrvList = mutableListOf<Int?>()
                            var timeInterval = 5
                            var historyDay = "TODAY"
                            
                            // 通过反射获取字段
                            val fields = info.javaClass.declaredFields
                            for (field in fields) {
                                field.isAccessible = true
                                val value = field.get(info)
                                Log.d(TAG, "🫀 [Kotlin] HRV字段: ${field.name} = $value (${value?.javaClass?.simpleName})")
                                
                                when (field.name) {
                                    "hrvList", "hrv", "list", "data" -> {
                                        when (value) {
                                            is List<*> -> {
                                                hrvList.addAll(value.map { it as? Int })
                                                Log.d(TAG, "✅ [Kotlin] 找到HRV列表，长度: ${hrvList.size}")
                                            }
                                            is IntArray -> {
                                                hrvList.addAll(value.map { it })
                                                Log.d(TAG, "✅ [Kotlin] 找到HRV数组，长度: ${hrvList.size}")
                                            }
                                            is Int -> {
                                                hrvList.add(value)
                                                Log.d(TAG, "✅ [Kotlin] 找到单个HRV值: $value")
                                            }
                                        }
                                    }
                                    "timeInterval", "interval" -> {
                                        if (value is Int) {
                                            timeInterval = value
                                            Log.d(TAG, "✅ [Kotlin] 找到时间间隔: $timeInterval")
                                        }
                                    }
                                    "historyDay", "day" -> {
                                        if (value != null) {
                                            historyDay = value.toString()
                                            Log.d(TAG, "✅ [Kotlin] 找到历史日期: $historyDay")
                                        }
                                    }
                                }
                            }
                            
                            if (hrvList.isNotEmpty()) {
                                val hrvData = mapOf<String, Any>(
                                    "hrvList" to hrvList,
                                    "timeInterval" to timeInterval,
                                    "historyDay" to historyDay
                                )
                                
                                Log.d(TAG, "📤 [Kotlin] 准备发送HRV数据到Flutter: ${hrvList.size} 个数据点")
                                mainHandler.post {
                                    try {
                                        methodChannel.invokeMethod("onHistoryHrvReceived", hrvData)
                                        Log.d(TAG, "✅ [Kotlin] HRV历史数据已发送到Flutter")
                                    } catch (e: Exception) {
                                        Log.e(TAG, "❌ [Kotlin] 发送HRV数据到Flutter失败: $e")
                                    }
                                }
                            } else {
                                Log.w(TAG, "⚠️ [Kotlin] HRV记录 $i 解析后为空，跳过")
                            }
                        } catch (e: Exception) {
                            Log.e(TAG, "❌ [Kotlin] 解析HRV记录 $i 失败: $e", e)
                        }
                    }
                }

                override fun onTimingInterval(interval: Int) {
                    Log.i(TAG, "🫀 [Kotlin数据回调] 定时HRV间隔: $interval 分钟")
                }

                override fun onTimingHrv(info: CRPTimingHrvInfo) {
                    Log.i(TAG, "🫀🫀🫀 [Kotlin数据回调] onTimingHrv() 收到定时HRV数据!!!")
                    Log.i(TAG, "🫀 [Kotlin数据回调] HRV原始数据: $info")
                    
                    // 通过反射获取字段（HRV数据不包含 timeInterval 字段）
                    try {
                        Log.i(TAG, "🫀 [Kotlin] 开始解析HRV数据...")
                        
                        val hrvList = info.javaClass.getDeclaredField("hrvList").apply { isAccessible = true }.get(info) as List<Int>
                        Log.i(TAG, "🫀 [Kotlin] 成功获取hrvList字段，长度: ${hrvList.size}")
                        
                        val historyDay = info.javaClass.getDeclaredField("historyDay").apply { isAccessible = true }.get(info)
                        Log.i(TAG, "🫀 [Kotlin] 成功获取historyDay字段: $historyDay")
                        
                        Log.i(TAG, "✅ [Kotlin] HRV数据解析完成: listSize=${hrvList.size}, historyDay=$historyDay")
                        
                        val hrvData = mapOf(
                            "hrvList" to hrvList,
                            "timeInterval" to 5, // 默认5分钟间隔
                            "historyDay" to historyDay.toString()
                        )
                        
                        Log.i(TAG, "📤 [Kotlin] 准备发送HRV数据到Flutter...")
                        mainHandler.post {
                            try {
                                methodChannel.invokeMethod("onHistoryHrvReceived", hrvData)
                                Log.i(TAG, "✅ [Kotlin] HRV数据已成功发送到Flutter!")
                            } catch (e: Exception) {
                                Log.e(TAG, "❌ [Kotlin] 发送HRV数据到Flutter失败: ${e.message}", e)
                            }
                        }
                    } catch (e: Exception) {
                        Log.e(TAG, "❌ [Kotlin] 解析定时HRV数据失败: ${e.message}", e)
                        Log.e(TAG, "❌ [Kotlin] 错误堆栈:", e)
                    }
                }
            })

            // 体温监听
            connection.setTempChangeListener(object : CRPTempChangeListener {
                override fun onTimingState(type: CRPTempType, interval: Int) {}

                override fun onHistoryTempChange(info: CRPHistoryTempInfo) {
                    mainHandler.post {
                        methodChannel.invokeMethod("onTempReceived", mapOf<String, Any>("rawData" to info.toString()))
                    }
                }

                override fun onMeasureComplete(temperature: Float) {
                    mainHandler.post {
                        methodChannel.invokeMethod("onTempMeasureComplete", mapOf<String, Any>("temperature" to temperature))
                    }
                }
            })

            // 压力监听
            connection.setStressChangeListener(object : CRPStressChangeListener {
                override fun onStressChange(stress: Int) {
                    Log.d(TAG, "😰😰😰 [Kotlin数据回调] onStressChange() 收到单个压力值: $stress")
                    mainHandler.post {
                        methodChannel.invokeMethod("onStressReceived", mapOf<String, Any>("stress" to stress))
                        Log.d(TAG, "✅ [Kotlin] 压力数据已发送到Flutter")
                    }
                }

                override fun onHistoryStressChange(list: MutableList<CRPHistoryStressInfo>) {
                    Log.d(TAG, "😰😰😰 [Kotlin数据回调] onHistoryStressChange() 收到历史压力数据: ${list.size} 条记录")
                    val stressList = list.map { info ->
                        mapOf<String, Any>("rawData" to info.toString())
                    }
                    mainHandler.post {
                        methodChannel.invokeMethod("onHistoryStressReceived", mapOf<String, Any>("data" to stressList))
                        Log.d(TAG, "✅ [Kotlin] 历史压力数据已发送到Flutter")
                    }
                }

                override fun onTimingInterval(interval: Int) {
                    Log.d(TAG, "😰 [Kotlin数据回调] 定时压力间隔: $interval 分钟")
                }

                override fun onTimingStress(info: CRPTimingStressInfo) {
                    Log.d(TAG, "😰😰😰 [Kotlin数据回调] onTimingStress() 收到定时压力数据")
                    try {
                        if (info != null && info.list != null) {
                            val historyDayName = try {
                                info.historyDay?.name ?: "TODAY"
                            } catch (e: Exception) {
                                "TODAY"
                            }
                            
                            Log.d(TAG, "😰 [Kotlin] 压力列表长度: ${info.list.size} 个数据点, 日期: $historyDayName")
                            
                            mainHandler.post {
                                methodChannel.invokeMethod("onStressListReceived", mapOf<String, Any>(
                                    "stressList" to info.list,
                                    "historyDay" to historyDayName
                                ))
                                Log.d(TAG, "✅ [Kotlin] 压力列表数据已发送到Flutter")
                            }
                        } else {
                            Log.w(TAG, "⚠️ [Kotlin] 压力数据为空: info=$info, list=${info?.list}")
                        }
                    } catch (e: Exception) {
                        Log.e(TAG, "❌ [Kotlin] 处理定时压力数据失败: $e", e)
                    }
                }
            })

            // 训练监听
            connection.setTrainingListener(object : CRPTrainingChangeListener {
                override fun onTrainingState(state: CRPTrainingState) {
                    mainHandler.post {
                        methodChannel.invokeMethod("onTrainingStateChanged", mapOf<String, Any>("state" to state.toString()))
                    }
                }

                override fun onTrainingState(trainingType: Int, state: CRPTrainingState) {
                    mainHandler.post {
                        methodChannel.invokeMethod("onTrainingStateChanged", mapOf<String, Any>(
                            "trainingType" to trainingType,
                            "state" to state.toString()
                        ))
                    }
                }

                override fun onGoalsReached(type: CRPGoalsType) {
                    mainHandler.post {
                        methodChannel.invokeMethod("onGoalsReached", mapOf<String, Any>("type" to type.toString()))
                    }
                }

                override fun onSupportTrainingList(list: MutableList<Int>) {
                    mainHandler.post {
                        methodChannel.invokeMethod("onSupportTrainingList", mapOf<String, Any>("trainingTypes" to list))
                    }
                }

                override fun onHistoryTrainingChange(list: MutableList<CRPHistoryTrainingInfo>) {
                    val trainingList = list.map { info ->
                        mapOf<String, Any>("rawData" to info.toString())
                    }
                    mainHandler.post {
                        methodChannel.invokeMethod("onHistoryTrainingReceived", mapOf<String, Any>("data" to trainingList))
                    }
                }

                override fun onTrainingChange(info: CRPTrainingInfo) {
                    mainHandler.post {
                        methodChannel.invokeMethod("onTrainingDataReceived", mapOf<String, Any>("rawData" to info.toString()))
                    }
                }

                override fun onHistoryDailyTrainingChange(list: MutableList<Long>) {}

                override fun onDailyTrainingChange(info: CRPDailyTrainingInfo) {}
            })

            // 动作详情监听
            connection.setActionDetailsListener(object : CRPActionDetailsListener {
                override fun onActionDetails(info: CRPActionDetailsInfo) {
                    mainHandler.post {
                        methodChannel.invokeMethod("onActionDetailsReceived", mapOf<String, Any>("rawData" to info.toString()))
                    }
                }
            })

            // 目标监听
            connection.setGoalsListener(object : CRPGoalsListener {
                override fun onGoalsAchieved(type: CRPGoalsType) {
                    mainHandler.post {
                        methodChannel.invokeMethod("onGoalsAchieved", mapOf<String, Any>("type" to type.toString()))
                    }
                }

                override fun onDailyGoals(info: CRPDailyGoalsInfo) {
                    mainHandler.post {
                        methodChannel.invokeMethod("onDailyGoalsReceived", mapOf<String, Any>("rawData" to info.toString()))
                    }
                }

                override fun onTrainingDayGoals(info: CRPTrainingDayGoalsInfo) {}
            })

            // 活动提醒监听
            connection.setActivityReminderListener(object : CRPActivityReminderListener {
                override fun onActivityReminder() {
                    mainHandler.post {
                        methodChannel.invokeMethod("onActivityReminder", null)
                    }
                }

                override fun onActivityReminderDetails(info: CRPActivityReminderInfo) {}
            })

            // 设备电压监听
            connection.setVoltageListener(object : CRPDeviceVoltageListener {
                override fun onHistoryVoltage(info: CRPVoltageInfo) {}
            })

            // 显示监听
            connection.setDisplayListener(object : CRPDisplayListener {
                override fun onAutoLock(seconds: Int) {}

                override fun onBrightness(brightness: Int) {
                    Log.d(TAG, "屏幕亮度: $brightness")
                }

                override fun onSupportDisplayFeature(list: MutableList<CRPDisplayFeature>) {
                    Log.d(TAG, "支持的显示特性: $list")
                }

                override fun onDisplayFeature(list: MutableList<CRPDisplayFeature>) {
                    Log.d(TAG, "当前显示特性: $list")
                }
            })
        }
    }

    /**
     * 连接成功后初始化设备 - 类似Java代码中的testSet()
     */
    private fun initializeDeviceAfterConnection() {
        Log.d(TAG, "📶 [设备初始化] 设备连接成功，开始初始化...")
        
        bleConnection?.let { connection ->
            try {
                // 查询固件版本
                Log.d(TAG, "🔄 [设备初始化] 调用 connection.queryFirmwareVersion()")
                connection.queryFirmwareVersion(object : CRPFirmwareVersionCallback {
                    override fun onVersion(version: String?) {
                        Log.d(TAG, "📋 [设备初始化] 固件版本回调: $version")
                        mainHandler.post {
                            methodChannel.invokeMethod("onFirmwareVersionReceived", mapOf<String, Any>("version" to (version ?: "")))
                        }
                    }
                })

                // 查询电池电量
                Log.d(TAG, "🔄 [设备初始化] 调用 connection.queryBattery()")
                connection.queryBattery()

                // 同步时间
                Log.d(TAG, "🔄 [设备初始化] 调用 connection.syncTime()")
                connection.syncTime()

                // 延迟获取所有数据，确保连接稳定
                mainHandler.postDelayed({
                    fetchAllDeviceData()
                }, 2000) // 延迟2秒

                Log.d(TAG, "✅ [设备初始化] 设备初始化完成")
            } catch (e: Exception) {
                Log.e(TAG, "❌ [设备初始化] 设备初始化失败", e)
            }
        } ?: run {
            Log.w(TAG, "⚠️ [设备初始化] bleConnection为null，无法初始化")
        }
    }

    /**
     * 获取所有设备数据 - 连接成功后自动调用
     */
    private fun fetchAllDeviceData() {
        Log.d(TAG, "📊 [数据获取] 开始获取所有设备数据...")
        
        bleConnection?.let { connection ->
            try {
                // 1. 获取活动步数数据
                Log.d(TAG, "🚶 [数据获取] 正在获取活动步数数据...")
                connection.queryCurrentSteps() // 获取当前步数
                connection.queryHistorySteps(CRPHistoryDay.TODAY) // 获取今日步数历史
                connection.queryHistoryStepsDetails(CRPHistoryDay.TODAY) // 获取今日步数详情
                
                // 2. 获取心率数据（查询最近14天）
                Log.d(TAG, "💓 [数据获取] 正在获取心率数据...")
                connection.queryHistoryHeartRate() // 获取历史心率数据
                connection.enableTimingHeartRate(15) // 开启定时心率监测（15分钟间隔）
                connection.queryTimingHeartRateState() // 查询定时心率状态
                // 查询最近14天的心率数据（异步延迟）
                for (day in 0..14) {
                    mainHandler.postDelayed({
                        val historyDay = getHistoryDayByOffset(day)
                        Log.d(TAG, "💓 [数据查询] 查询心率数据: day=$day, historyDay=$historyDay")
                        connection.queryHistoryTimingHeartRate(historyDay)
                    }, (day * 100).toLong()) // 每个请求间隔100ms
                }
                
                // 3. 获取心率变异性(HRV)数据（查询最近14天）
                Log.d(TAG, "💗 [数据获取] 正在获取心率变异性数据...")
                connection.queryHistoryHrv() // 获取历史HRV数据
                connection.enableTimingHrv(15) // 开启定时HRV监测（15分钟间隔）
                connection.queryTimingHrvState() // 查询定时HRV状态
                // 查询最近14天的HRV数据
                for (day in 0..14) {
                    mainHandler.postDelayed({
                        val historyDay = getHistoryDayByOffset(day)
                        connection.queryHistoryTimingHrv(historyDay)
                    }, (day * 100).toLong()) // 每个请求间隔100ms
                }
                
                // 4. 获取压力数据（查询最近14天）
                Log.d(TAG, "😰 [数据获取] 正在获取压力数据...")
                connection.queryHistoryStress() // 获取历史压力数据
                connection.enableTimingStress(15) // 开启定时压力监测（15分钟间隔）
                connection.queryTimingStressState() // 查询定时压力状态
                // 查询最近14天的压力数据
                for (day in 0..14) {
                    mainHandler.postDelayed({
                        val historyDay = getHistoryDayByOffset(day)
                        connection.queryHistoryTimingStress(historyDay)
                    }, (day * 100).toLong()) // 每个请求间隔100ms
                }
                
                // 5. 获取锻炼记录数据
                Log.d(TAG, "🏃 [数据获取] 正在获取锻炼记录数据...")
                connection.queryHistoryDailyTraining() // 获取今日训练数据
                
                // 6. 获取睡眠数据
                Log.d(TAG, "😴 [数据获取] 正在获取睡眠数据...")
                // 【移除】不再调用 queryHistorySleep，因为它也会触发 onHistorySleepListChange 回调
                // connection.queryHistorySleep(CRPHistoryDay.TODAY) // 获取今日睡眠数据
                connection.queryHistorySleepList() // 获取睡眠历史列表（会触发验证接口）- 唯一调用
                connection.querySleepChronotype() // 获取睡眠时型
                
                // 【说明】只保留 queryHistorySleepList()，避免重复触发回调
                // queryHistorySleepList() 会返回所有睡眠记录，包括今日的
                
                // 7. 获取血氧数据（查询最近14天）
                Log.d(TAG, "🩸 [数据获取] 正在获取血氧数据...")
                connection.queryHistoryBloodOxygen() // 获取历史血氧数据
                connection.enableTimingBloodOxygen(4) // 开启定时血氧监测（4小时间隔）
                connection.queryTimingBloodOxygenState() // 查询定时血氧状态
                // 查询最近14天的血氧数据
                for (day in 0..14) {
                    mainHandler.postDelayed({
                        val historyDay = getHistoryDayByOffset(day)
                        connection.queryHistoryTimingBloodOxygen(historyDay)
                    }, (day * 100).toLong()) // 每个请求间隔100ms
                }
                
                // 获取活动详情数据（查询最近14天）
                Log.d(TAG, "📈 [数据获取] 正在获取活动详情数据...")
                for (day in 0..14) {
                    mainHandler.postDelayed({
                        val historyDay = getHistoryDayByOffset(day)
                        connection.queryActionDetails(historyDay)
                    }, (day * 100).toLong()) // 每个请求间隔100ms
                }
                
                Log.d(TAG, "✅ [数据获取] 所有数据获取请求已发送，等待设备响应...")
                
                // 通知Flutter端开始数据获取
                mainHandler.post {
                    methodChannel.invokeMethod("onDataFetchStarted", mapOf<String, Any>("status" to "started"))
                }
                
            } catch (e: Exception) {
                Log.e(TAG, "❌ [数据获取] 获取设备数据失败", e)
                mainHandler.post {
                    methodChannel.invokeMethod("onDataFetchError", mapOf<String, Any>("error" to (e.message ?: "未知错误")))
                }
            }
        } ?: run {
            Log.w(TAG, "⚠️ [数据获取] bleConnection为null，无法获取数据")
        }
    }

    /**
     * 手动获取所有设备数据 - 供Flutter端调用
     */
    private fun fetchAllDeviceDataManual(result: MethodChannel.Result) {
        Log.d(TAG, "📞 [方法调用] fetchAllDeviceDataManual() 开始执行")
        
        if (!isDeviceConnected()) {
            Log.w(TAG, "❌ [方法调用] fetchAllDeviceDataManual() 失败: 设备未连接")
            result.error("DEVICE_NOT_CONNECTED", "设备未连接", null)
            return
        }

        try {
            Log.d(TAG, "🔄 [方法调用] fetchAllDeviceDataManual() 调用 fetchAllDeviceData()")
            fetchAllDeviceData()
            
            Log.d(TAG, "✅ [方法调用] fetchAllDeviceDataManual() 执行成功")
            result.success(true)
        } catch (e: Exception) {
            Log.e(TAG, "❌ [方法调用] fetchAllDeviceDataManual() 执行失败", e)
            result.error("FETCH_FAILED", "获取所有设备数据失败: ${e.message}", null)
        }
    }

    /**
     * 根据天数偏移获取CRPHistoryDay枚举
     * @param dayOffset 天数偏移（0=今天，1=昨天，2=前天...）
     */
    private fun getHistoryDayByOffset(dayOffset: Int): CRPHistoryDay {
        return when (dayOffset) {
            0 -> CRPHistoryDay.TODAY
            1 -> CRPHistoryDay.YESTERDAY
            2 -> CRPHistoryDay.DAYS_AGO_2
            3 -> CRPHistoryDay.DAYS_AGO_3
            4 -> CRPHistoryDay.DAYS_AGO_4
            5 -> CRPHistoryDay.DAYS_AGO_5
            6 -> CRPHistoryDay.DAYS_AGO_6
            7 -> CRPHistoryDay.DAYS_AGO_7
            8 -> CRPHistoryDay.DAYS_AGO_8
            9 -> CRPHistoryDay.DAYS_AGO_9
            10 -> CRPHistoryDay.DAYS_AGO_10
            11 -> CRPHistoryDay.DAYS_AGO_11
            12 -> CRPHistoryDay.DAYS_AGO_12
            13 -> CRPHistoryDay.DAYS_AGO_13
            14 -> CRPHistoryDay.DAYS_AGO_14
            else -> CRPHistoryDay.TODAY
        }
    }

    /**
     * 将CRPHistoryDay枚举转换为字符串格式
     */
    private fun convertHistoryDayToString(historyDay: CRPHistoryDay): String {
        return when (historyDay) {
            CRPHistoryDay.TODAY -> "TODAY"
            CRPHistoryDay.YESTERDAY -> "YESTERDAY"
            CRPHistoryDay.DAYS_AGO_2 -> "DAYS_AGO_2"
            CRPHistoryDay.DAYS_AGO_3 -> "DAYS_AGO_3"
            CRPHistoryDay.DAYS_AGO_4 -> "DAYS_AGO_4"
            CRPHistoryDay.DAYS_AGO_5 -> "DAYS_AGO_5"
            CRPHistoryDay.DAYS_AGO_6 -> "DAYS_AGO_6"
            CRPHistoryDay.DAYS_AGO_7 -> "DAYS_AGO_7"
            CRPHistoryDay.DAYS_AGO_8 -> "DAYS_AGO_8"
            CRPHistoryDay.DAYS_AGO_9 -> "DAYS_AGO_9"
            CRPHistoryDay.DAYS_AGO_10 -> "DAYS_AGO_10"
            CRPHistoryDay.DAYS_AGO_11 -> "DAYS_AGO_11"
            CRPHistoryDay.DAYS_AGO_12 -> "DAYS_AGO_12"
            CRPHistoryDay.DAYS_AGO_13 -> "DAYS_AGO_13"
            CRPHistoryDay.DAYS_AGO_14 -> "DAYS_AGO_14"
            else -> "TODAY" // 默认返回今天
        }
    }

    /**
     * 查找今天在历史睡眠列表中的所有索引
     */
    private fun findTodayIndices(list: MutableList<Long>): List<Int> {
        val todayIndices = mutableListOf<Int>()
        val todayCalendar = java.util.Calendar.getInstance()
        todayCalendar.set(java.util.Calendar.HOUR_OF_DAY, 0)
        todayCalendar.set(java.util.Calendar.MINUTE, 0)
        todayCalendar.set(java.util.Calendar.SECOND, 0)
        todayCalendar.set(java.util.Calendar.MILLISECOND, 0)
        val todayStart = todayCalendar.timeInMillis
        
        val tomorrowCalendar = java.util.Calendar.getInstance()
        tomorrowCalendar.add(java.util.Calendar.DAY_OF_YEAR, 1)
        tomorrowCalendar.set(java.util.Calendar.HOUR_OF_DAY, 0)
        tomorrowCalendar.set(java.util.Calendar.MINUTE, 0)
        tomorrowCalendar.set(java.util.Calendar.SECOND, 0)
        tomorrowCalendar.set(java.util.Calendar.MILLISECOND, 0)
        val tomorrowStart = tomorrowCalendar.timeInMillis
        
        Log.d(TAG, "🔍 [时间戳解析] 查找今天索引列表，今天开始时间戳: $todayStart, 明天开始时间戳: $tomorrowStart")
        
        for (i in list.indices) {
            val timestamp = list[i]
            if (timestamp > 0) {
                // 检查时间戳是否在今天范围内
                if (timestamp >= todayStart && timestamp < tomorrowStart) {
                    val date = java.util.Date(timestamp)
                    Log.d(TAG, "✅ [时间戳解析] 找到今天索引: $i, 时间戳: $timestamp, 日期: $date")
                    todayIndices.add(i)
                }
            }
        }
        
        Log.d(TAG, "📅 [时间戳解析] 今天索引列表: $todayIndices")
        return todayIndices
    }

    /**
     * 查找昨天在历史睡眠列表中的所有索引
     */
    private fun findYesterdayIndices(list: MutableList<Long>): List<Int> {
        val yesterdayIndices = mutableListOf<Int>()
        val yesterdayCalendar = java.util.Calendar.getInstance()
        yesterdayCalendar.add(java.util.Calendar.DAY_OF_YEAR, -1)
        yesterdayCalendar.set(java.util.Calendar.HOUR_OF_DAY, 0)
        yesterdayCalendar.set(java.util.Calendar.MINUTE, 0)
        yesterdayCalendar.set(java.util.Calendar.SECOND, 0)
        yesterdayCalendar.set(java.util.Calendar.MILLISECOND, 0)
        val yesterdayStart = yesterdayCalendar.timeInMillis
        
        val todayCalendar = java.util.Calendar.getInstance()
        todayCalendar.set(java.util.Calendar.HOUR_OF_DAY, 0)
        todayCalendar.set(java.util.Calendar.MINUTE, 0)
        todayCalendar.set(java.util.Calendar.SECOND, 0)
        todayCalendar.set(java.util.Calendar.MILLISECOND, 0)
        val todayStart = todayCalendar.timeInMillis
        
        Log.d(TAG, "🔍 [时间戳解析] 查找昨天索引列表，昨天开始时间戳: $yesterdayStart, 今天开始时间戳: $todayStart")
        
        for (i in list.indices) {
            val timestamp = list[i]
            if (timestamp > 0) {
                // 检查时间戳是否在昨天范围内
                if (timestamp >= yesterdayStart && timestamp < todayStart) {
                    val date = java.util.Date(timestamp)
                    Log.d(TAG, "✅ [时间戳解析] 找到昨天索引: $i, 时间戳: $timestamp, 日期: $date")
                    yesterdayIndices.add(i)
                }
            }
        }
        
        Log.d(TAG, "📅 [时间戳解析] 昨天索引列表: $yesterdayIndices")
        return yesterdayIndices
    }

    /**
     * 判断睡眠详情是否为今天的数据
     */
    private fun isTodaySleep(info: CRPSleepDetailsInfo): Boolean {
        // 获取今天的开始时间戳（00:00:00）
        val todayCalendar = java.util.Calendar.getInstance()
        todayCalendar.set(java.util.Calendar.HOUR_OF_DAY, 0)
        todayCalendar.set(java.util.Calendar.MINUTE, 0)
        todayCalendar.set(java.util.Calendar.SECOND, 0)
        todayCalendar.set(java.util.Calendar.MILLISECOND, 0)
        val todayStart = todayCalendar.timeInMillis
        
        // 获取明天的开始时间戳（00:00:00）
        val tomorrowCalendar = java.util.Calendar.getInstance()
        tomorrowCalendar.add(java.util.Calendar.DAY_OF_YEAR, 1)
        tomorrowCalendar.set(java.util.Calendar.HOUR_OF_DAY, 0)
        tomorrowCalendar.set(java.util.Calendar.MINUTE, 0)
        tomorrowCalendar.set(java.util.Calendar.SECOND, 0)
        tomorrowCalendar.set(java.util.Calendar.MILLISECOND, 0)
        val tomorrowStart = tomorrowCalendar.timeInMillis
        
        // 检查开始时间或结束时间是否在今天范围内
        val startTime = info.startDate.time
        val endTime = info.endDate.time
        
        val isToday = (startTime >= todayStart && startTime < tomorrowStart) ||
                     (endTime >= todayStart && endTime < tomorrowStart) ||
                     (startTime < todayStart && endTime >= tomorrowStart) // 跨天睡眠
        
        Log.d(TAG, "📅 [睡眠详情判断] 开始时间: ${info.startDate} (${startTime}), 结束时间: ${info.endDate} (${endTime})")
        Log.d(TAG, "📅 [睡眠详情判断] 今天开始: $todayStart, 明天开始: $tomorrowStart, 是否为今天: $isToday")
        return isToday
    }


    /**
     * 查询当前步数数据
     */
    private fun queryCurrentSteps(result: MethodChannel.Result) {
        Log.d(TAG, "📞 [方法调用] queryCurrentSteps() 开始执行")
        
        if (!isDeviceConnected()) {
            Log.w(TAG, "❌ [方法调用] queryCurrentSteps() 失败: 设备未连接")
            result.error("DEVICE_NOT_CONNECTED", "设备未连接", null)
            return
        }

        try {
            Log.d(TAG, "🔄 [方法调用] queryCurrentSteps() 调用 bleConnection.queryCurrentSteps()")
            bleConnection?.queryCurrentSteps()
            
            Log.d(TAG, "✅ [方法调用] queryCurrentSteps() 执行成功")
            result.success(true)
        } catch (e: Exception) {
            Log.e(TAG, "❌ [方法调用] queryCurrentSteps() 执行失败", e)
            result.error("QUERY_FAILED", "查询当前步数失败: ${e.message}", null)
        }
    }



    /**
     * 查询指定日期的步数数据
     */
    private fun queryStepsForDate(historyDayString: String?, result: MethodChannel.Result) {
        Log.d(TAG, "📞 [方法调用] queryStepsForDate() 开始执行, 参数: historyDayString=$historyDayString")
        
        if (!isDeviceConnected()) {
            Log.w(TAG, "❌ [方法调用] queryStepsForDate() 失败: 设备未连接")
            result.error("DEVICE_NOT_CONNECTED", "设备未连接", null)
            return
        }

        if (historyDayString == null) {
            Log.w(TAG, "❌ [方法调用] queryStepsForDate() 失败: 历史日期参数为空")
            result.error("INVALID_PARAMETER", "历史日期参数不能为空", null)
            return
        }

        try {
            val historyDay = when {
                historyDayString == "TODAY" -> CRPHistoryDay.TODAY
                historyDayString == "YESTERDAY" -> CRPHistoryDay.YESTERDAY
                historyDayString.startsWith("DAYS_AGO_") -> {
                    val daysAgo = historyDayString.substring("DAYS_AGO_".length).toIntOrNull()
                    when (daysAgo) {
                        2 -> CRPHistoryDay.DAYS_AGO_2
                        3 -> CRPHistoryDay.DAYS_AGO_3
                        4 -> CRPHistoryDay.DAYS_AGO_4
                        5 -> CRPHistoryDay.DAYS_AGO_5
                        6 -> CRPHistoryDay.DAYS_AGO_6
                        7 -> CRPHistoryDay.DAYS_AGO_7
                        8 -> CRPHistoryDay.DAYS_AGO_8
                        9 -> CRPHistoryDay.DAYS_AGO_9
                        10 -> CRPHistoryDay.DAYS_AGO_10
                        11 -> CRPHistoryDay.DAYS_AGO_11
                        12 -> CRPHistoryDay.DAYS_AGO_12
                        13 -> CRPHistoryDay.DAYS_AGO_13
                        14 -> CRPHistoryDay.DAYS_AGO_14
                        else -> {
                            result.error("INVALID_HISTORY_DAY", "不支持的天数: $daysAgo", null)
                            return
                        }
                    }
                }
                else -> {
                    result.error("INVALID_HISTORY_DAY", "无效的历史日期: $historyDayString", null)
                    return
                }
            }

            // 查询指定日期的步数数据
            Log.d(TAG, "🔄 [方法调用] queryStepsForDate() 调用 bleConnection.queryHistorySteps($historyDay)")
            bleConnection?.queryHistorySteps(historyDay)
            
            Log.d(TAG, "🔄 [方法调用] queryStepsForDate() 调用 bleConnection.queryHistoryStepsDetails($historyDay)")
            bleConnection?.queryHistoryStepsDetails(historyDay)
            
            Log.d(TAG, "✅ [方法调用] queryStepsForDate() 执行成功, 日期: $historyDayString")
            result.success(true)
        } catch (e: Exception) {
            Log.e(TAG, "❌ [方法调用] queryStepsForDate() 执行失败", e)
            result.error("QUERY_FAILED", "查询指定日期步数失败: ${e.message}", null)
        }
    }

    /**
     * 查询睡眠数据
     */
    private fun querySleep(result: MethodChannel.Result) {
        Log.d(TAG, "📞 [方法调用] querySleep() 开始执行")
        
        if (!isDeviceConnected()) {
            Log.w(TAG, "❌ [方法调用] querySleep() 失败: 设备未连接")
            result.error("DEVICE_NOT_CONNECTED", "设备未连接", null)
            return
        }

        try {
            Log.d(TAG, "🔄 [方法调用] querySleep() 调用 bleConnection.queryHistorySleepList()")
            bleConnection?.queryHistorySleepList()
            
            Log.d(TAG, "✅ [方法调用] querySleep() 执行成功")
            result.success(true)
        } catch (e: Exception) {
            Log.e(TAG, "❌ [方法调用] querySleep() 执行失败", e)
            result.error("QUERY_FAILED", "查询睡眠数据失败: ${e.message}", null)
        }
    }

    /**
     * 查询心率数据
     */
    private fun queryHeartRate(result: MethodChannel.Result) {
        Log.d(TAG, "📞 [方法调用] queryHeartRate() 开始执行")
        
        if (!isDeviceConnected()) {
            Log.w(TAG, "❌ [方法调用] queryHeartRate() 失败: 设备未连接")
            result.error("DEVICE_NOT_CONNECTED", "设备未连接", null)
            return
        }

        try {
            // 确保心率监听器已设置
            if (!isHeartRateListenerSet) {
                Log.d(TAG, "🔄 [方法调用] queryHeartRate() 心率监听器未设置，先设置监听器")
                setupHeartRateListener()
            }
            
            Log.d(TAG, "🔄 [方法调用] queryHeartRate() 调用 bleConnection.queryHistoryHeartRate()")
            bleConnection?.queryHistoryHeartRate()
            
            Log.d(TAG, "✅ [方法调用] queryHeartRate() 执行成功")
            result.success(true)
        } catch (e: Exception) {
            Log.e(TAG, "❌ [方法调用] queryHeartRate() 执行失败", e)
            result.error("QUERY_FAILED", "查询心率数据失败: ${e.message}", null)
        }
    }

    /**
     * 查询电池电量
     */
    private fun queryBattery(result: MethodChannel.Result) {
        Log.d(TAG, "📞 [方法调用] queryBattery() 开始执行")
        
        if (!isDeviceConnected()) {
            Log.w(TAG, "❌ [方法调用] queryBattery() 失败: 设备未连接")
            result.error("DEVICE_NOT_CONNECTED", "设备未连接", null)
            return
        }

        try {
            Log.d(TAG, "🔄 [方法调用] queryBattery() 调用 bleConnection.queryBattery()")
            bleConnection?.queryBattery()
            
            Log.d(TAG, "✅ [方法调用] queryBattery() 执行成功")
            result.success(true)
        } catch (e: Exception) {
            Log.e(TAG, "❌ [方法调用] queryBattery() 执行失败", e)
            result.error("QUERY_FAILED", "查询电池电量失败: ${e.message}", null)
        }
    }

    /**
     * 开始心率测量
     */
    private fun startHeartRateMeasure(result: MethodChannel.Result) {
        Log.d(TAG, "📞 [方法调用] startHeartRateMeasure() 开始执行")
        
        if (!isDeviceConnected()) {
            Log.w(TAG, "❌ [方法调用] startHeartRateMeasure() 失败: 设备未连接")
            result.error("DEVICE_NOT_CONNECTED", "设备未连接", null)
            return
        }

        try {
            Log.d(TAG, "🔄 [方法调用] startHeartRateMeasure() 调用 bleConnection.startMeasureHeartRate()")
            bleConnection?.startMeasureHeartRate()
            
            Log.d(TAG, "✅ [方法调用] startHeartRateMeasure() 执行成功")
            result.success(true)
        } catch (e: Exception) {
            Log.e(TAG, "❌ [方法调用] startHeartRateMeasure() 执行失败", e)
            result.error("MEASURE_FAILED", "开始心率测量失败: ${e.message}", null)
        }
    }

    /**
     * 停止心率测量
     */
    private fun stopHeartRateMeasure(result: MethodChannel.Result) {
        Log.d(TAG, "📞 [方法调用] stopHeartRateMeasure() 开始执行")
        
        if (!isDeviceConnected()) {
            Log.w(TAG, "❌ [方法调用] stopHeartRateMeasure() 失败: 设备未连接")
            result.error("DEVICE_NOT_CONNECTED", "设备未连接", null)
            return
        }

        try {
            Log.d(TAG, "🔄 [方法调用] stopHeartRateMeasure() 调用 bleConnection.stopMeasureHeartRate()")
            bleConnection?.stopMeasureHeartRate()
            
            Log.d(TAG, "✅ [方法调用] stopHeartRateMeasure() 执行成功")
            result.success(true)
        } catch (e: Exception) {
            Log.e(TAG, "❌ [方法调用] stopHeartRateMeasure() 执行失败", e)
            result.error("MEASURE_FAILED", "停止心率测量失败: ${e.message}", null)
        }
    }

    /**
     * 同步时间
     */
    private fun syncTime(result: MethodChannel.Result) {
        Log.d(TAG, "📞 [方法调用] syncTime() 开始执行")
        
        if (!isDeviceConnected()) {
            Log.w(TAG, "❌ [方法调用] syncTime() 失败: 设备未连接")
            result.error("DEVICE_NOT_CONNECTED", "设备未连接", null)
            return
        }

        try {
            Log.d(TAG, "🔄 [方法调用] syncTime() 调用 bleConnection.syncTime()")
            bleConnection?.syncTime()
            
            Log.d(TAG, "✅ [方法调用] syncTime() 执行成功")
            result.success(true)
        } catch (e: Exception) {
            Log.e(TAG, "❌ [方法调用] syncTime() 执行失败", e)
            result.error("SYNC_FAILED", "同步时间失败: ${e.message}", null)
        }
    }

    /**
     * 查询血氧数据
     */
    private fun queryBloodOxygen(result: MethodChannel.Result) {
        Log.d(TAG, "📞 [方法调用] queryBloodOxygen() 开始执行")
        
        if (!isDeviceConnected()) {
            Log.w(TAG, "❌ [方法调用] queryBloodOxygen() 失败: 设备未连接")
            result.error("DEVICE_NOT_CONNECTED", "设备未连接", null)
            return
        }

        try {
            Log.d(TAG, "🔄 [方法调用] queryBloodOxygen() 调用 bleConnection.queryHistoryBloodOxygen()")
            bleConnection?.queryHistoryBloodOxygen()
            
            Log.d(TAG, "✅ [方法调用] queryBloodOxygen() 执行成功")
            result.success(true)
        } catch (e: Exception) {
            Log.e(TAG, "❌ [方法调用] queryBloodOxygen() 执行失败", e)
            result.error("QUERY_FAILED", "查询血氧数据失败: ${e.message}", null)
        }
    }

    /**
     * 查询指定日期的血氧数据
     */
    private fun queryBloodOxygenForDate(historyDayString: String?, result: MethodChannel.Result) {
        Log.d(TAG, "📞 [方法调用] queryBloodOxygenForDate() 开始执行, 参数: historyDayString=$historyDayString")
        
        if (!isDeviceConnected()) {
            Log.w(TAG, "❌ [方法调用] queryBloodOxygenForDate() 失败: 设备未连接")
            result.error("DEVICE_NOT_CONNECTED", "设备未连接", null)
            return
        }

        if (historyDayString == null) {
            Log.w(TAG, "❌ [方法调用] queryBloodOxygenForDate() 失败: 历史日期参数为空")
            result.error("INVALID_PARAMETER", "历史日期参数不能为空", null)
            return
        }

        try {
            val historyDay = when {
                historyDayString == "TODAY" -> CRPHistoryDay.TODAY
                historyDayString == "YESTERDAY" -> CRPHistoryDay.YESTERDAY
                historyDayString.startsWith("DAYS_AGO_") -> {
                    val daysAgo = historyDayString.substring("DAYS_AGO_".length).toIntOrNull()
                    when (daysAgo) {
                        2 -> CRPHistoryDay.DAYS_AGO_2
                        3 -> CRPHistoryDay.DAYS_AGO_3
                        4 -> CRPHistoryDay.DAYS_AGO_4
                        5 -> CRPHistoryDay.DAYS_AGO_5
                        6 -> CRPHistoryDay.DAYS_AGO_6
                        7 -> CRPHistoryDay.DAYS_AGO_7
                        8 -> CRPHistoryDay.DAYS_AGO_8
                        9 -> CRPHistoryDay.DAYS_AGO_9
                        10 -> CRPHistoryDay.DAYS_AGO_10
                        11 -> CRPHistoryDay.DAYS_AGO_11
                        12 -> CRPHistoryDay.DAYS_AGO_12
                        13 -> CRPHistoryDay.DAYS_AGO_13
                        14 -> CRPHistoryDay.DAYS_AGO_14
                        else -> {
                            Log.w(TAG, "❌ [方法调用] queryBloodOxygenForDate() 失败: 不支持的天数 $daysAgo")
                            result.error("INVALID_PARAMETER", "不支持的天数: $daysAgo", null)
                            return
                        }
                    }
                }
                else -> {
                    Log.w(TAG, "❌ [方法调用] queryBloodOxygenForDate() 失败: 无效的历史日期格式 $historyDayString")
                    result.error("INVALID_PARAMETER", "无效的历史日期格式: $historyDayString", null)
                    return
                }
            }

            // 查询血氧数据（参考DeviceActivity.java的实现）
            Log.d(TAG, "🔄 [方法调用] queryBloodOxygenForDate() 调用 bleConnection.queryHistoryBloodOxygen()")
            bleConnection?.queryHistoryBloodOxygen()
            
            // 同时查询定时血氧数据
            Log.d(TAG, "🔄 [方法调用] queryBloodOxygenForDate() 调用 bleConnection.queryHistoryTimingBloodOxygen($historyDay)")
            bleConnection?.queryHistoryTimingBloodOxygen(historyDay)
            
            Log.d(TAG, "✅ [方法调用] queryBloodOxygenForDate() 执行成功, 日期: $historyDayString")
            result.success(true)
        } catch (e: Exception) {
            Log.e(TAG, "❌ [方法调用] queryBloodOxygenForDate() 执行失败", e)
            result.error("QUERY_FAILED", "查询指定日期血氧数据失败: ${e.message}", null)
        }
    }

    /**
     * 开始血氧测量
     */
    private fun startBloodOxygenMeasure(result: MethodChannel.Result) {
        Log.d(TAG, "   [方法调用] startBloodOxygenMeasure() 开始执行")
        
        if (!isDeviceConnected()) {
            Log.w(TAG, "❌ [方法调用] startBloodOxygenMeasure() 失败: 设备未连接")
            result.error("DEVICE_NOT_CONNECTED", "设备未连接", null)
            return
        }

        try {
            Log.d(TAG, "🔄 [方法调用] startBloodOxygenMeasure() 调用 bleConnection.startMeasureBloodOxygen()")
            bleConnection?.startMeasureBloodOxygen()
            
            Log.d(TAG, "✅ [方法调用] startBloodOxygenMeasure() 执行成功")
            result.success(true)
        } catch (e: Exception) {
            Log.e(TAG, "❌ [方法调用] startBloodOxygenMeasure() 执行失败", e)
            result.error("MEASURE_FAILED", "开始血氧测量失败: ${e.message}", null)
        }
    }

    /**
     * 停止血氧测量
     */
    private fun stopBloodOxygenMeasure(result: MethodChannel.Result) {
        if (!isDeviceConnected()) {
            result.error("DEVICE_NOT_CONNECTED", "设备未连接", null)
            return
        }

        try {
            bleConnection?.stopMeasureBloodOxygen()
            Log.d(TAG, "已停止血氧测量")
            result.success(true)
        } catch (e: Exception) {
            Log.e(TAG, "停止血氧测量失败", e)
            result.error("MEASURE_FAILED", "停止血氧测量失败: ${e.message}", null)
        }
    }

    /**
     * 查询HRV数据
     */
    private fun queryHrv(result: MethodChannel.Result) {
        Log.i(TAG, "🫀🫀🫀 [Kotlin查询] queryHrv() 开始执行")
        
        if (!isDeviceConnected()) {
            Log.w(TAG, "❌ [Kotlin查询] queryHrv() 失败: 设备未连接")
            result.error("DEVICE_NOT_CONNECTED", "设备未连接", null)
            return
        }

        try {
            Log.i(TAG, "🫀 [Kotlin查询] 调用 bleConnection.queryHistoryHrv()")
            bleConnection?.queryHistoryHrv()
            
            Log.i(TAG, "🫀 [Kotlin查询] 调用 bleConnection.queryHistoryTimingHrv(TODAY)")
            bleConnection?.queryHistoryTimingHrv(com.crrepa.ble.conn.type.CRPHistoryDay.TODAY)
            
            Log.i(TAG, "🫀 [Kotlin查询] 调用 bleConnection.queryTimingHrvState()")
            bleConnection?.queryTimingHrvState()
            
            Log.i(TAG, "✅ [Kotlin查询] HRV数据查询请求已全部发送，等待SDK回调...")
            result.success(true)
        } catch (e: Exception) {
            Log.e(TAG, "❌ [Kotlin查询] 查询HRV数据失败: ${e.message}", e)
            result.error("QUERY_FAILED", "查询HRV数据失败: ${e.message}", null)
        }
    }

    /**
     * 开始HRV测量
     */
    private fun startHrvMeasure(result: MethodChannel.Result) {
        if (!isDeviceConnected()) {
            result.error("DEVICE_NOT_CONNECTED", "设备未连接", null)
            return
        }

        try {
            bleConnection?.startMeasureHrv()
            Log.d(TAG, "已开始HRV测量")
            result.success(true)
        } catch (e: Exception) {
            Log.e(TAG, "开始HRV测量失败", e)
            result.error("MEASURE_FAILED", "开始HRV测量失败: ${e.message}", null)
        }
    }

    /**
     * 停止HRV测量
     */
    private fun stopHrvMeasure(result: MethodChannel.Result) {
        if (!isDeviceConnected()) {
            result.error("DEVICE_NOT_CONNECTED", "设备未连接", null)
            return
        }

        try {
            bleConnection?.stopMeasureHrv()
            Log.d(TAG, "已停止HRV测量")
            result.success(true)
        } catch (e: Exception) {
            Log.e(TAG, "停止HRV测量失败", e)
            result.error("MEASURE_FAILED", "停止HRV测量失败: ${e.message}", null)
        }
    }

    /**
     * 查询压力数据
     */
    private fun queryStress(result: MethodChannel.Result) {
        if (!isDeviceConnected()) {
            result.error("DEVICE_NOT_CONNECTED", "设备未连接", null)
            return
        }

        try {
            bleConnection?.queryHistoryStress()
            Log.d(TAG, "已发送压力数据查询请求")
            result.success(true)
        } catch (e: Exception) {
            Log.e(TAG, "查询压力数据失败", e)
            result.error("QUERY_FAILED", "查询压力数据失败: ${e.message}", null)
        }
    }

    /**
     * 开始压力测量
     */
    private fun startStressMeasure(result: MethodChannel.Result) {
        if (!isDeviceConnected()) {
            result.error("DEVICE_NOT_CONNECTED", "设备未连接", null)
            return
        }

        try {
            bleConnection?.startMeasureStress()
            Log.d(TAG, "已开始压力测量")
            result.success(true)
        } catch (e: Exception) {
            Log.e(TAG, "开始压力测量失败", e)
            result.error("MEASURE_FAILED", "开始压力测量失败: ${e.message}", null)
        }
    }

    /**
     * 停止压力测量
     */
    private fun stopStressMeasure(result: MethodChannel.Result) {
        if (!isDeviceConnected()) {
            result.error("DEVICE_NOT_CONNECTED", "设备未连接", null)
            return
        }

        try {
            bleConnection?.stopMeasureStress()
            Log.d(TAG, "已停止压力测量")
            result.success(true)
        } catch (e: Exception) {
            Log.e(TAG, "停止压力测量失败", e)
            result.error("MEASURE_FAILED", "停止压力测量失败: ${e.message}", null)
        }
    }

    /**
     * 查询今日压力列表数据
     */
    private fun queryTodayStressList(result: MethodChannel.Result) {
        if (!isDeviceConnected()) {
            result.error("DEVICE_NOT_CONNECTED", "设备未连接", null)
            return
        }

        try {
            bleConnection?.let { connection ->
                // 根据Java示例，按照正确的顺序调用SDK方法
                try {
                    
                    connection.queryTimingStressState()
                    Log.d(TAG, "已查询定时压力采集状态")
                    
                    connection.queryHistoryTimingStress(CRPHistoryDay.TODAY)
                    Log.d(TAG, "已发送今日定时压力数据查询请求")
                } catch (e: Exception) {
                    connection.queryHistoryStress()
                    Log.d(TAG, "已发送历史压力数据查询请求")
                }
            }
            
            result.success(true)
        } catch (e: Exception) {
            Log.e(TAG, "查询今日压力列表数据失败", e)
            result.error("QUERY_FAILED", "查询今日压力列表数据失败: ${e.message}", null)
        }
    }

    /**
     * 查询训练数据
     */
    private fun queryTraining(result: MethodChannel.Result) {
        if (!isDeviceConnected()) {
            result.error("DEVICE_NOT_CONNECTED", "设备未连接", null)
            return
        }

        try {
            bleConnection?.queryHistoryTraining()
            bleConnection?.querySupportTraining()
            Log.d(TAG, "已发送训练数据查询请求")
            result.success(true)
        } catch (e: Exception) {
            Log.e(TAG, "查询训练数据失败", e)
            result.error("QUERY_FAILED", "查询训练数据失败: ${e.message}", null)
        }
    }

    /**
     * 开始训练
     */
    private fun startTraining(trainingType: Int, result: MethodChannel.Result) {
        if (!isDeviceConnected()) {
            result.error("DEVICE_NOT_CONNECTED", "设备未连接", null)
            return
        }

        try {
            val goalsInfo = CRPTrainingGoalsInfo(CRPGoalsType.NOT_GOALS, 0)
            bleConnection?.startTraining(trainingType.toByte(), goalsInfo)
            Log.d(TAG, "已开始训练，类型: $trainingType")
            result.success(true)
        } catch (e: Exception) {
            Log.e(TAG, "开始训练失败", e)
            result.error("TRAINING_FAILED", "开始训练失败: ${e.message}", null)
        }
    }

    /**
     * 停止训练
     */
    private fun stopTraining(result: MethodChannel.Result) {
        if (!isDeviceConnected()) {
            result.error("DEVICE_NOT_CONNECTED", "设备未连接", null)
            return
        }

        try {
            val goalsInfo = CRPTrainingGoalsInfo(CRPGoalsType.NOT_GOALS, 0)
            bleConnection?.sendTrainingState(CRPTrainingState.END, goalsInfo)
            Log.d(TAG, "已停止训练")
            result.success(true)
        } catch (e: Exception) {
            Log.e(TAG, "停止训练失败", e)
            result.error("TRAINING_FAILED", "停止训练失败: ${e.message}", null)
        }
    }

    /**
     * 发送用户信息
     */
    private fun sendUserInfo(weight: Int, height: Int, gender: Int, age: Int, stride: Int, result: MethodChannel.Result) {
        if (!isDeviceConnected()) {
            result.error("DEVICE_NOT_CONNECTED", "设备未连接", null)
            return
        }

        try {
            val userInfo = CRPUserInfo(weight, height, gender, age, stride)
            bleConnection?.sendUserInfo(userInfo)
            Log.d(TAG, "已发送用户信息: 体重=$weight, 身高=$height, 性别=$gender, 年龄=$age, 步长=$stride")
            result.success(true)
        } catch (e: Exception) {
            Log.e(TAG, "发送用户信息失败", e)
            result.error("SEND_FAILED", "发送用户信息失败: ${e.message}", null)
        }
    }

    /**
     * 检查设备是否已连接
     */
    private fun isDeviceConnected(): Boolean {
        return bleDevice?.isConnected == true
    }

    /**
     * 检查是否有蓝牙权限
     */
    private fun hasBluetoothPermissions(): Boolean {
        val isAndroid12Plus = Build.VERSION.SDK_INT >= Build.VERSION_CODES.S
        Log.d(TAG, "检查蓝牙权限 - Android版本: ${Build.VERSION.SDK_INT}, 是否Android12+: $isAndroid12Plus")
        
        return if (isAndroid12Plus) {
            // Android 12+ 需要新的蓝牙权限
            val scanPermission = ContextCompat.checkSelfPermission(activity, Manifest.permission.BLUETOOTH_SCAN) == PackageManager.PERMISSION_GRANTED
            val connectPermission = ContextCompat.checkSelfPermission(activity, Manifest.permission.BLUETOOTH_CONNECT) == PackageManager.PERMISSION_GRANTED
            val locationPermission = ContextCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
            
            Log.d(TAG, "权限状态 - BLUETOOTH_SCAN: $scanPermission, BLUETOOTH_CONNECT: $connectPermission, ACCESS_FINE_LOCATION: $locationPermission")
            
            scanPermission && connectPermission && locationPermission
        } else {
            // Android 11 及以下版本使用位置权限
            val locationPermission = ContextCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
            Log.d(TAG, "权限状态 - ACCESS_FINE_LOCATION: $locationPermission")
            locationPermission
        }
    }

    /**
     * 请求蓝牙权限
     */
    private fun requestBluetoothPermissions() {
        val permissions = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            arrayOf(
                Manifest.permission.BLUETOOTH_SCAN,
                Manifest.permission.BLUETOOTH_CONNECT,
                Manifest.permission.ACCESS_FINE_LOCATION
            )
        } else {
            arrayOf(
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.ACCESS_COARSE_LOCATION
            )
        }

        Log.d(TAG, "请求蓝牙权限: ${permissions.contentToString()}")
        
        // 检查是否有权限可以请求
        val needsRequest = permissions.any { permission ->
            ActivityCompat.shouldShowRequestPermissionRationale(activity, permission) ||
            ContextCompat.checkSelfPermission(activity, permission) != PackageManager.PERMISSION_GRANTED
        }
        
        if (needsRequest) {
            ActivityCompat.requestPermissions(activity, permissions, BLUETOOTH_PERMISSION_REQUEST_CODE)
        } else {
            // 权限可能被永久拒绝了
            Log.e(TAG, "蓝牙权限可能被永久拒绝，请到设置中手动开启")
            pendingScanResult?.error("PERMISSION_PERMANENTLY_DENIED", "蓝牙权限被永久拒绝，请到设置中手动开启", null)
            pendingScanResult = null
        }
    }

    /**
     * 处理权限请求结果
     */
    fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
        if (requestCode == BLUETOOTH_PERMISSION_REQUEST_CODE) {
            val allPermissionsGranted = grantResults.all { it == PackageManager.PERMISSION_GRANTED }
            
            pendingScanResult?.let { result ->
                if (allPermissionsGranted) {
                    Log.d(TAG, "蓝牙权限已授予，开始扫描")
                    performScan(result)
                } else {
                    Log.e(TAG, "蓝牙权限被拒绝")
                    result.error("PERMISSION_DENIED", "蓝牙权限被拒绝，无法扫描设备", null)
                }
                pendingScanResult = null
            }
        }
    }

    /**
     * 根据索引查询训练详情
     */
    private fun queryTrainingByIndex(index: Int, result: MethodChannel.Result) {
        if (!isDeviceConnected()) {
            result.error("DEVICE_NOT_CONNECTED", "设备未连接", null)
            return
        }

        try {
            bleConnection?.let { connection ->
                Log.d(TAG, "查询训练详情: index=$index")
                connection.queryTraining(index)
                result.success(true)
            } ?: run {
                result.error("CONNECTION_NULL", "连接对象为空", null)
            }
        } catch (e: Exception) {
            Log.e(TAG, "查询训练详情失败", e)
            result.error("QUERY_FAILED", "查询训练详情失败: ${e.message}", null)
        }
    }

    /**
     * 查询锻炼详情
     */
    private fun queryExerciseDetails(result: MethodChannel.Result) {
        if (!isDeviceConnected()) {
            result.error("DEVICE_NOT_CONNECTED", "设备未连接", null)
            return
        }

        try {
            bleConnection?.let { connection ->
                // 设置训练监听器
                connection.setTrainingListener(object : CRPTrainingChangeListener {
                    override fun onTrainingState(state: CRPTrainingState) {
                        Log.d(TAG, "训练状态: $state")
                    }

                    override fun onTrainingState(trainingType: Int, state: CRPTrainingState) {
                        Log.d(TAG, "训练状态: 类型=$trainingType, 状态=$state")
                    }

                    override fun onGoalsReached(type: CRPGoalsType) {
                        Log.d(TAG, "目标达成: $type")
                    }

                    override fun onSupportTrainingList(list: MutableList<Int>) {
                        Log.d(TAG, "支持的训练类型: $list")
                    }

                    override fun onHistoryTrainingChange(list: MutableList<CRPHistoryTrainingInfo>) {
                        Log.d(TAG, "历史训练数据: ${list.size} 条记录")
                        if (list.isNotEmpty()) {
                            // 查询具体的训练详情
                            connection.queryTraining(0) // 查询第一条记录的详情
                        }
                    }

                    override fun onTrainingChange(info: CRPTrainingInfo) {
                        Log.d(TAG, "训练详情: $info")
                        processAndReportTrainingData(info)
                    }

                    override fun onHistoryDailyTrainingChange(list: MutableList<Long>) {
                        Log.d(TAG, "历史每日训练: $list")
                    }

                    override fun onDailyTrainingChange(info: CRPDailyTrainingInfo) {
                        Log.d(TAG, "每日训练详情: $info")
                        processAndReportDailyTrainingData(info)
                    }
                })

                // 查询历史训练数据
                connection.queryHistoryTraining()
                
                // 查询今日训练数据
                connection.queryHistoryDailyTraining()
                
                Log.d(TAG, "已开始查询锻炼详情")
                result.success(true)
            } ?: run {
                result.error("CONNECTION_NULL", "连接对象为空", null)
            }
        } catch (e: Exception) {
            Log.e(TAG, "查询锻炼详情失败", e)
            result.error("QUERY_FAILED", "查询锻炼详情失败: ${e.message}", null)
        }
    }

    /**
     * 处理训练数据并上报给API
     */
    private fun processAndReportTrainingData(trainingInfo: CRPTrainingInfo) {
        try {
            // 获取设备SN
            val deviceSn = bleDevice?.address ?: "unknown"
            
            // 构建锻炼详情数据
            val exerciseType = getTrainingType(trainingInfo)
            val startDate = getTrainingStartTime(trainingInfo)
            val endDate = getTrainingEndTime(trainingInfo)
            val exerciseTime = getTrainingDuration(trainingInfo) // 锻炼时长（秒）
            val exerciseCalorie = getTrainingCalories(trainingInfo) // 消耗卡路里
            val recordDate = getCurrentDate()
            
            Log.d(TAG, "锻炼详情 - 类型: $exerciseType, 开始: $startDate, 结束: $endDate, 时长: $exerciseTime, 卡路里: $exerciseCalorie")
            
            // 发送锻炼详情到Flutter
            val exerciseData = mapOf<String, Any>(
                "deviceSn" to deviceSn,
                "exerciseType" to exerciseType,
                "startDate" to startDate,
                "endDate" to endDate,
                "exerciseTime" to exerciseTime,
                "exerciseCalorie" to exerciseCalorie,
                "recordDate" to recordDate,
                "rawInfo" to trainingInfo.toString()
            )
            
            mainHandler.post {
                methodChannel.invokeMethod("onExerciseDetailsReceived", exerciseData)
            }
            
        } catch (e: Exception) {
            Log.e(TAG, "处理训练数据失败", e)
        }
    }

    /**
     * 处理每日训练数据并上报给API
     */
    private fun processAndReportDailyTrainingData(dailyTrainingInfo: CRPDailyTrainingInfo) {
        try {
            // 获取设备SN
            val deviceSn = bleDevice?.address ?: "unknown"
            
            // 构建锻炼详情数据
            val exerciseType = "daily_summary" // 每日汇总类型
            val recordDate = getCurrentDate()
            val exerciseTime = getDailyTrainingDuration(dailyTrainingInfo) // 总锻炼时长
            val exerciseCalorie = getDailyTrainingCalories(dailyTrainingInfo) // 总消耗卡路里
            
            Log.d(TAG, "每日锻炼汇总 - 时长: $exerciseTime, 卡路里: $exerciseCalorie")
            
            // 发送每日锻炼汇总到Flutter
            val dailyExerciseData = mapOf<String, Any>(
                "deviceSn" to deviceSn,
                "exerciseType" to exerciseType,
                "startDate" to recordDate,
                "endDate" to recordDate,
                "exerciseTime" to exerciseTime,
                "exerciseCalorie" to exerciseCalorie,
                "recordDate" to recordDate,
                "rawInfo" to dailyTrainingInfo.toString()
            )
            
            mainHandler.post {
                methodChannel.invokeMethod("onDailyExerciseDetailsReceived", dailyExerciseData)
            }
            
        } catch (e: Exception) {
            Log.e(TAG, "处理每日训练数据失败", e)
        }
    }

    /**
     * 格式化时间戳为日期字符串
     */
    private fun formatTimestamp(timestamp: Long): String {
        return if (timestamp <= 0) {
            getCurrentDate()
        } else {
            try {
                val sdf = java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss", java.util.Locale.getDefault())
                sdf.format(java.util.Date(timestamp * 1000L)) // 假设时间戳是秒
            } catch (e: Exception) {
                Log.e(TAG, "格式化时间戳失败", e)
                getCurrentDate()
            }
        }
    }

    /**
     * 获取当前日期字符串
     */
    private fun getCurrentDate(): String {
        val sdf = java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss", java.util.Locale.getDefault())
        return sdf.format(java.util.Date())
    }

    /**
     * 安全获取训练类型
     */
    private fun getTrainingType(trainingInfo: CRPTrainingInfo): String {
        return try {
            // 尝试通过反射获取训练类型
            val fields = trainingInfo.javaClass.declaredFields
            for (field in fields) {
                field.isAccessible = true
                when (field.name) {
                    "trainingType", "type" -> {
                        val value = field.get(trainingInfo)
                        if (value != null) {
                            return value.toString()
                        }
                    }
                }
            }
            "unknown"
        } catch (e: Exception) {
            Log.e(TAG, "获取训练类型失败", e)
            "unknown"
        }
    }

    /**
     * 安全获取训练开始时间
     */
    private fun getTrainingStartTime(trainingInfo: CRPTrainingInfo): String {
        return try {
            val fields = trainingInfo.javaClass.declaredFields
            for (field in fields) {
                field.isAccessible = true
                when (field.name) {
                    "startTime", "start" -> {
                        val value = field.get(trainingInfo)
                        if (value is Long) {
                            return formatTimestamp(value)
                        }
                    }
                }
            }
            getCurrentDate()
        } catch (e: Exception) {
            Log.e(TAG, "获取训练开始时间失败", e)
            getCurrentDate()
        }
    }

    /**
     * 安全获取训练结束时间
     */
    private fun getTrainingEndTime(trainingInfo: CRPTrainingInfo): String {
        return try {
            val fields = trainingInfo.javaClass.declaredFields
            for (field in fields) {
                field.isAccessible = true
                when (field.name) {
                    "endTime", "end" -> {
                        val value = field.get(trainingInfo)
                        if (value is Long) {
                            return formatTimestamp(value)
                        }
                    }
                }
            }
            getCurrentDate()
        } catch (e: Exception) {
            Log.e(TAG, "获取训练结束时间失败", e)
            getCurrentDate()
        }
    }

    /**
     * 安全获取训练时长
     */
    private fun getTrainingDuration(trainingInfo: CRPTrainingInfo): Int {
        return try {
            val fields = trainingInfo.javaClass.declaredFields
            for (field in fields) {
                field.isAccessible = true
                when (field.name) {
                    "duration", "time", "totalTime" -> {
                        val value = field.get(trainingInfo)
                        if (value is Int) {
                            return value
                        } else if (value is Long) {
                            return value.toInt()
                        }
                    }
                }
            }
            0
        } catch (e: Exception) {
            Log.e(TAG, "获取训练时长失败", e)
            0
        }
    }

    /**
     * 安全获取训练卡路里
     */
    private fun getTrainingCalories(trainingInfo: CRPTrainingInfo): Int {
        return try {
            val fields = trainingInfo.javaClass.declaredFields
            for (field in fields) {
                field.isAccessible = true
                when (field.name) {
                    "calories", "calorie", "energy" -> {
                        val value = field.get(trainingInfo)
                        if (value is Int) {
                            return value
                        } else if (value is Long) {
                            return value.toInt()
                        }
                    }
                }
            }
            0
        } catch (e: Exception) {
            Log.e(TAG, "获取训练卡路里失败", e)
            0
        }
    }

    /**
     * 安全获取每日训练时长
     */
    private fun getDailyTrainingDuration(dailyTrainingInfo: CRPDailyTrainingInfo): Int {
        return try {
            val fields = dailyTrainingInfo.javaClass.declaredFields
            for (field in fields) {
                field.isAccessible = true
                when (field.name) {
                    "duration", "time", "totalTime" -> {
                        val value = field.get(dailyTrainingInfo)
                        if (value is Int) {
                            return value
                        } else if (value is Long) {
                            return value.toInt()
                        }
                    }
                }
            }
            0
        } catch (e: Exception) {
            Log.e(TAG, "获取每日训练时长失败", e)
            0
        }
    }

    /**
     * 安全获取每日训练卡路里
     */
    private fun getDailyTrainingCalories(dailyTrainingInfo: CRPDailyTrainingInfo): Int {
        return try {
            val fields = dailyTrainingInfo.javaClass.declaredFields
            for (field in fields) {
                field.isAccessible = true
                when (field.name) {
                    "calories", "calorie", "energy" -> {
                        val value = field.get(dailyTrainingInfo)
                        if (value is Int) {
                            return value
                        } else if (value is Long) {
                            return value.toInt()
                        }
                    }
                }
            }
            0
        } catch (e: Exception) {
            Log.e(TAG, "获取每日训练卡路里失败", e)
            0
        }
    }

    /**
     * 清理资源
     */
    fun dispose() {
        bleDevice?.disconnect()
        bleConnection?.close()
        Log.d(TAG, "RingDataChannel 资源已清理")
    }


    
    
    /**
     * 根据索引查询睡眠数据（供Flutter调用）
     */
    private fun querySleepDataByIndex(index: Int, result: MethodChannel.Result) {
        Log.d(TAG, "📞 [方法调用] querySleepDataByIndex() 开始执行, index=$index")
        
        // 【关键修复】检查是否有查询正在进行
        if (isSleepQueryInProgress) {
            Log.w(TAG, "⚠️ [方法调用] querySleepDataByIndex() 失败: 上一个查询还在进行中")
            result.error("QUERY_IN_PROGRESS", "上一个查询还在进行中，请稍后重试", null)
            return
        }
        
        if (!isDeviceConnected()) {
            Log.w(TAG, "❌ [方法调用] querySleepDataByIndex() 失败: 设备未连接")
            result.error("DEVICE_NOT_CONNECTED", "设备未连接", null)
            return
        }

        try {
            bleConnection?.let { connection ->
                // 【关键修复】设置查询锁
                isSleepQueryInProgress = true
                
                // 创建索引的局部副本
                val queryIndex = index
                currentSleepQueryIndex = queryIndex
                
                // 立即查询
                Log.d(TAG, "🔄 [步骤1/2] 调用 querySleepDetails($queryIndex)")
                connection.querySleepDetails(queryIndex)
                
                Log.d(TAG, "🔄 [步骤2/2] 调用 querySleepInfo($queryIndex)")
                connection.querySleepInfo(queryIndex)
                
                // 【关键修复】2秒后自动释放锁（防止卡住）
                mainHandler.postDelayed({
                    if (isSleepQueryInProgress) {
                        Log.w(TAG, "⚠️ [超时] 2秒后自动释放查询锁")
                        isSleepQueryInProgress = false
                    }
                }, 2000)
                
                Log.d(TAG, "✅ [方法调用] querySleepDataByIndex() 执行成功，等待数据回调")
                result.success(true)
            } ?: run {
                Log.w(TAG, "❌ [方法调用] querySleepDataByIndex() 失败: bleConnection为null")
                result.error("CONNECTION_NULL", "连接对象为空", null)
            }
        } catch (e: Exception) {
            Log.e(TAG, "❌ [方法调用] querySleepDataByIndex() 执行失败", e)
            isSleepQueryInProgress = false // 异常时释放锁
            result.error("QUERY_FAILED", "查询睡眠数据失败: ${e.message}", null)
        }
    }

    // ==================== 训练功能方法 ====================

    /**
     * 设置训练监听器
     */
    private fun setupTrainingListener(
        connection: CRPBleConnection,
        methodChannel: MethodChannel,
        mainHandler: Handler
    ) {
        connection.setTrainingListener(object : CRPTrainingChangeListener {
            // 1. 返回设备支持的训练类型列表 (SDK expects List<Int>)
            override fun onSupportTrainingList(list: MutableList<Int>) {
                Log.d(TAG, "🏃 [训练监听] 收到支持的训练类型: ${list.size} 种")
                
                val trainingTypes = list.map { it.toString() }.toList()
                Log.d(TAG, "📋 [训练监听] 训练类型列表: $trainingTypes")
                
                mainHandler.post {
                    methodChannel.invokeMethod("onSupportTrainingListReceived", mapOf<String, Any>(
                        "trainingTypes" to trainingTypes
                    ))
                }
            }

            // 2a. 返回当前训练状态 (single parameter)
            override fun onTrainingState(state: CRPTrainingState) {
                Log.d(TAG, "🏃 [训练监听] 训练状态变化: $state")
                
                val stateString = state.toString().lowercase()
                
                mainHandler.post {
                    methodChannel.invokeMethod("onTrainingStateChanged", mapOf<String, Any>(
                        "state" to stateString
                    ))
                }
            }

            // 2b. 返回当前训练状态 (two parameters - overloaded method)
            override fun onTrainingState(type: Int, state: CRPTrainingState) {
                Log.d(TAG, "🏃 [训练监听] 训练状态变化: type=$type, state=$state")
                
                val stateString = state.toString().lowercase()
                
                mainHandler.post {
                    methodChannel.invokeMethod("onTrainingStateChanged", mapOf<String, Any>(
                        "type" to type,
                        "state" to stateString
                    ))
                }
            }

            // 3a. 返回历史训练记录列表
            override fun onHistoryTrainingChange(list: MutableList<CRPHistoryTrainingInfo>) {
                Log.d(TAG, "🏃 [训练监听] 收到历史训练记录: ${list.size} 条")
                
                val historyList = list.mapIndexed { index, info ->
                    // Use reflection to get fields since we don't know the exact structure
                    try {
                        mapOf<String, Any>(
                            "type" to (info.type ?: 0),
                            "startTime" to (info.startTime ?: 0L),
                            "index" to index,
                            "rawInfo" to info.toString()
                        )
                    } catch (e: Exception) {
                        Log.e(TAG, "❌ 解析训练记录失败: $e")
                        mapOf<String, Any>(
                            "index" to index,
                            "rawInfo" to info.toString()
                        )
                    }
                }
                
                mainHandler.post {
                    methodChannel.invokeMethod("onHistoryTrainingReceived", mapOf<String, Any>(
                        "historyList" to historyList
                    ))
                }
            }

            // 3b. 返回每日历史训练记录列表 (SDK expects List<Long> - timestamps)
            override fun onHistoryDailyTrainingChange(list: MutableList<Long>) {
                Log.d(TAG, "🏃 [训练监听] 收到每日历史训练记录: ${list.size} 条")
                
                val dailyHistoryList = list.mapIndexed { index, timestamp ->
                    mapOf<String, Any>(
                        "index" to index,
                        "timestamp" to timestamp
                    )
                }
                
                mainHandler.post {
                    methodChannel.invokeMethod("onHistoryDailyTrainingReceived", mapOf<String, Any>(
                        "dailyHistoryList" to dailyHistoryList
                    ))
                }
            }

            // 3c. 返回每日训练变化 (required by SDK interface)
            override fun onDailyTrainingChange(info: CRPDailyTrainingInfo) {
                Log.d(TAG, "🏃 [训练监听] 收到每日训练变化: $info")
                
                try {
                    val dailyTrainingData = mapOf<String, Any>(
                        "rawInfo" to info.toString()
                    )
                    
                    mainHandler.post {
                        methodChannel.invokeMethod("onDailyTrainingChange", dailyTrainingData)
                    }
                } catch (e: Exception) {
                    Log.e(TAG, "❌ 解析每日训练变化失败: $e")
                }
            }

            // 4. 返回训练详情 (SDK uses CRPTrainingInfo, not CRPTrainingDetailsInfo)
            override fun onTrainingChange(info: CRPTrainingInfo) {
                Log.d(TAG, "🏃 [训练监听] 收到训练详情: $info")
                
                // Use reflection to extract fields
                try {
                    val trainingDetails = mutableMapOf<String, Any>()
                    trainingDetails["rawInfo"] = info.toString()
                    
                    // Try to get common fields
                    val fields = info.javaClass.declaredFields
                    for (field in fields) {
                        field.isAccessible = true
                        val value = field.get(info)
                        if (value != null) {
                            trainingDetails[field.name] = value
                        }
                    }
                    
                    mainHandler.post {
                        methodChannel.invokeMethod("onTrainingDetailsReceived", trainingDetails)
                    }
                } catch (e: Exception) {
                    Log.e(TAG, "❌ 解析训练详情失败: $e")
                }
            }

            // 5. 训练目标达成回调
            override fun onGoalsReached(type: CRPGoalsType) {
                Log.d(TAG, "🎯 [训练监听] 训练目标达成: $type")
                
                val goalType = type.toString().lowercase()
                
                mainHandler.post {
                    methodChannel.invokeMethod("onTrainingGoalReached", mapOf<String, Any>(
                        "goalType" to goalType
                    ))
                }
            }
        })
        
        Log.d(TAG, "✅ 训练监听器设置完成")
    }

    /**
     * 查询支持的训练类型
     */
    private fun querySupportTraining(
        connection: CRPBleConnection?,
        result: MethodChannel.Result
    ) {
        if (connection == null) {
            Log.w(TAG, "❌ 查询支持的训练类型失败: 设备未连接")
            result.error("NOT_CONNECTED", "设备未连接", null)
            return
        }
        
        try {
            connection.querySupportTraining()
            Log.d(TAG, "✅ 已发送查询支持的训练类型请求")
            result.success(true)
        } catch (e: Exception) {
            Log.e(TAG, "❌ 查询支持的训练类型失败", e)
            result.error("QUERY_FAILED", "查询失败: ${e.message}", null)
        }
    }

    /**
     * 开始训练
     */
    private fun startTraining(
        connection: CRPBleConnection?,
        type: Byte,
        goalsInfo: CRPTrainingGoalsInfo?,
        result: MethodChannel.Result
    ) {
        if (connection == null) {
            Log.w(TAG, "❌ 开始训练失败: 设备未连接")
            result.error("NOT_CONNECTED", "设备未连接", null)
            return
        }
        
        try {
            connection.startTraining(type, goalsInfo)
            Log.d(TAG, "✅ 已发送开始训练请求: type=$type")
            result.success(true)
        } catch (e: Exception) {
            Log.e(TAG, "❌ 开始训练失败", e)
            result.error("START_FAILED", "开始训练失败: ${e.message}", null)
        }
    }

    /**
     * 修改训练状态
     */
    private fun sendTrainingState(
        connection: CRPBleConnection?,
        state: CRPTrainingState,
        goalsInfo: CRPTrainingGoalsInfo?,
        result: MethodChannel.Result
    ) {
        if (connection == null) {
            Log.w(TAG, "❌ 修改训练状态失败: 设备未连接")
            result.error("NOT_CONNECTED", "设备未连接", null)
            return
        }
        
        try {
            connection.sendTrainingState(state, goalsInfo)
            Log.d(TAG, "✅ 已发送修改训练状态请求: state=$state")
            result.success(true)
        } catch (e: Exception) {
            Log.e(TAG, "❌ 修改训练状态失败", e)
            result.error("STATE_CHANGE_FAILED", "修改状态失败: ${e.message}", null)
        }
    }

    /**
     * 查询当前训练状态
     */
    private fun queryTrainingState(
        connection: CRPBleConnection?,
        result: MethodChannel.Result
    ) {
        if (connection == null) {
            Log.w(TAG, "❌ 查询训练状态失败: 设备未连接")
            result.error("NOT_CONNECTED", "设备未连接", null)
            return
        }
        
        try {
            connection.queryTrainingState()
            Log.d(TAG, "✅ 已发送查询训练状态请求")
            result.success(true)
        } catch (e: Exception) {
            Log.e(TAG, "❌ 查询训练状态失败", e)
            result.error("QUERY_FAILED", "查询失败: ${e.message}", null)
        }
    }

    /**
     * 查询历史训练记录
     */
    private fun queryHistoryTraining(
        connection: CRPBleConnection?,
        result: MethodChannel.Result
    ) {
        if (connection == null) {
            Log.w(TAG, "❌ 查询历史训练记录失败: 设备未连接")
            result.error("NOT_CONNECTED", "设备未连接", null)
            return
        }
        
        try {
            connection.queryHistoryTraining()
            Log.d(TAG, "✅ 已发送查询历史训练记录请求")
            result.success(true)
        } catch (e: Exception) {
            Log.e(TAG, "❌ 查询历史训练记录失败", e)
            result.error("QUERY_FAILED", "查询失败: ${e.message}", null)
        }
    }

    /**
     * 根据ID查询训练详情
     */
    private fun queryTrainingById(
        connection: CRPBleConnection?,
        id: Int,
        result: MethodChannel.Result
    ) {
        if (connection == null) {
            Log.w(TAG, "❌ 查询训练详情失败: 设备未连接")
            result.error("NOT_CONNECTED", "设备未连接", null)
            return
        }
        
        try {
            // SDK expects Int
            connection.queryTraining(id)
            Log.d(TAG, "✅ 已发送查询训练详情请求: id=$id")
            result.success(true)
        } catch (e: Exception) {
            Log.e(TAG, "❌ 查询训练详情失败", e)
            result.error("QUERY_FAILED", "查询失败: ${e.message}", null)
        }
    }

}

